(有点启发 by this answer 虽然不相关)
我一直被告知(并且被告知)保持 const
的正确性,即使对于短暂的变量也是有值(value)的和良好的做法,例如:
const std::string a = "Hello world";
代替
std::string a = "Hello world";
这个:
- 更清楚地表达意图。
- 确保变量是不可变的,因此将它传递给某个可能会更改它的函数会使编译器对你大喊大叫。
- 可能由于编译器优化而提高性能。
尽管自从现代 C++ 引入复制省略以来,一直有 a few clauses in the standard允许编译器调用移动构造函数而不是复制构造函数:
In the following copy-initialization contexts, a move operation might be used instead of a copy operation:
(3.1) If the expression in a
return
statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, or(3.2) if the operand of a
throw-expression
([expr.throw]) is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosingtry-block
(if there is one),
这是否意味着在遇到这种省略适用的情况时,使用具有非默认复制/移动构造函数的 const
对象实际上会降低性能而不是提高性能?
最佳答案
Does this mean there can actually be a performance penalty for using const objects with a non-default copy/move constructor
可能是的。当返回本地对象时,constness 会阻止使用引用规则允许的移动构造。尽管在实践中可能不存在性能损失,因为无论变量是否为 const,NRVO 仍可能省略整个复制/移动。
但 NRVO 并不能保证,而且不一定总是可行 - 或者根本不启用(调试构建),因此在按值返回局部变量时使用非常量可能是值得的。
关于c++ - 非平凡变量的常量正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55126988/