这个问题是相关问题 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/