c++ - C++ 编译器能否对用于返回值的命名 const 变量执行 RVO?

标签 c++ c++17 return-value-optimization nrvo

这个问题是相关问题 shown here 的一个细微变体.

在 C++17 中,我有一个局部变量,我想将其设为 const 以证明它根据 Scott Meyers Effective C++ item 3 recommendation to use const whenever possible 创建后未修改。 :

#include <string>

std::string foo()
{
    const std::string str = "bar";

    return str;
}

int main()
{
    std::string txt = foo();
}

编译器可以为 txt 执行(命名的)返回值优化吗? , 即使 str 的类型与 foo 的返回类型不同由于常量差异?

最佳答案

命名返回值优化由 C++17 中指定的复制省略启用 [class.copy.elision] .这里的相关部分是[class.copy.elision]/1.1 :

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. […]

  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler ([except.handle])) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call's return object

[…]

强调我的。因此,允许编译器在此处执行优化。和 a quick test似乎可以验证编译器实际上会在这里执行此优化......

请注意,const 可能仍然存在问题。如果编译器不执行复制省略(这里只允许,不保证会发生;即使在 C++17 中,因为 return 语句中的表达式不是纯右值),const 通常会阻止对象被移动(通常不能从 const 对象移动)...

关于c++ - C++ 编译器能否对用于返回值的命名 const 变量执行 RVO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194688/

相关文章:

c++ - 对新对象使用相同的引用

c++ - 从模板函数返回匿名结构(用于结构化绑定(bind))

c++ - 什么是复制省略和返回值优化?

c++ - 为什么 std::basic_ostream::operator<< 不是 const 限定的?

C++ 的 Pythonic 预处理器

C++/编译程序 fatal error : QtGui/qwidget. h: No such file or directory

C++ 17 友元函数声明和内联命名空间

c++ - 不同编译器引用未知边界数组的奇怪行为

c++ - RVO 何时显示出最大的性能影响?

c++ - 从 std::tuple 解包的值的返回值优化