Overloading operators : const vs non-const return type : any difference of performance?

前端 未结 3 2022
余生分开走
余生分开走 2021-02-08 18:58

If we go to the wikipedia article about C++ operators, we have as an example :

Addition : a + b -> T T::operator +(const T& b) const;

S

3条回答
  •  旧巷少年郎
    2021-02-08 19:15

    Since you're returning a temporary rvalue instance of type T, this statement doesn't do anything unless there are some global side-effects in the assignment operation, such as modifications to static variables that are data members of the type T, output to a terminal, etc. Therefore depending on the type, and whether the assignment operator is a compiler default assignment operator, this entire operation may be safely elided in an optimization pass. If there is a user-defined assignment operator for type T, then the assignment operation won't be elided, but as mentioned before, unless there are global side-effects, this won't do anything past the life-time of the statement's execution since you are not storing the value of c in an object that resides in a named and accessible memory location.

    Keep in mind that if you do declare the return T type as const, and your operator method is not a const class method, you will disable certain types of operator chaining, as well as a host of other useful things, such as calling methods that have side-effects. For instance:

    (a+b).print(); //assuming print() is non-const method
    

    or assuming operator+ is not a const class method,

    d = (a+b) + c;
    

提交回复
热议问题