且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重载操作符:const vs非const返回类型:任何性能差异?

更新时间:2023-11-11 20:11:16

在C ++ 03中,没有更好的机会来优化两个选项之一,这将是一个风格选择的问题(我自己不相信整个返回 const 以避免不可能的错误)。

This is an interesting question. In C++03, there would be no better chances to optimize with either of the two options and it would be a matter of style choice (I myself don't believe on the whole return by const to avoid unlikely errors).

另一方面,在C ++ 11中,它可能会有影响。特别是,如果你的类型支持移动操作,并且返回值的复制/移出不能被省略,那么通过返回 const 你实际上是禁用移动 *

In C++11, on the other hand, it might actually have an impact. In particular, if your type supports move operations, and the copy/move out of the returned value cannot be elided, then by returning by const you are effectively disabling moves *

// T is move assignable, with the usual declaration of a move assignment operator
T f();
const T g();
int main() {
   T t;
   t = f();     // can move
   t = g();     // cannot move!!!
}



在你的特殊情况下, em>意味着你,如果他们是 std :: array (或其他数组与自动存储),那么它们不能移动,所以这不会是一个选项,但如果大数组是动态分配的内存,移动将比复制更有效。请注意,在C ++ 11中是在线,而不是没有 const ,可能会导致性能损失。

In your particular case, it depends on what large arrays means for you, if they are std::array (or otherwise arrays with automatic storage), then they cannot be moved, so this would not be an option anyway, but if the large arrays are dynamically allocated memory, moving will be much more efficient than copying. Note that in C++11 is the presence rather than the absence of const that can cause a performance penalty.

* 这不是 100%true ,如果移动赋值运算符 rvalue-reference const ,则可以移动。但是标准库中没有一个类型以这种方式接受参数,我不会指望人们这样做(在 move 里面需要 const_cast / em>操作(构造函数/赋值),它只是没有意义:如果你计划从它移动(偷),为什么会声称不修改它

* This is not 100% true, if the move assignment operator took the argument by rvalue-reference to const, then it could be moved. But none of the types in the standard library takes the argument this way, and I would not expect people to do it either (it would require const_cast inside the move operation (either constructor/assignment) and it just makes no sense: if you plan on moving (stealing) from it, why would you claim not to modify it??