非平凡变量的常量正确性

Const-correctness for non trivial variables

(有点启发虽然不相关)

我一直被告知(并且被告知)保持 const-正确性,即使对于短暂的变量也是有价值的和好的做法,例如:

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 enclosing try-block (if there is one),

这是否意味着使用具有非默认 copy/move 构造函数的 const 对象实际上会导致性能下降,而不是在遇到适用于这种省略的情况时增加性能?

Does this mean there can actually be a performance penalty for using const objects with a non-default copy/move constructor

可能是的。当返回本地对象时,constness 会阻止使用引用规则允许的移动构造。尽管在实践中可能不存在性能损失,因为 NRVO 可能仍会忽略整个 copy/move 变量是否为 const。

虽然不能保证 NRVO,而且不一定总是可行 - 或者根本不启用(调试版本),因此在按值返回局部变量时使用非常量可能是值得的。