When Can Returning a Const Value Be Beneficial?
Item 3 of Effective C advocates returning values as const in some cases. However, this practice has raised questions regarding its usefulness and potential drawbacks.
In the specific example provided:
const Object myFunc() { return myObject; }
Using const restricts the use of the returned value as it prevents you from performing certain operations on unnamed const objects, such as arithmetic expressions.
The purpose of returning by const value was primarily to prevent unintended bool casts of the return value. However, in modern C , the use of the explicit keyword is recommended for this purpose.
Moreover, in scenarios where non-const operations could be performed on the returned object, returning by const value prevents accidental calls to such operations on temporarily created objects. For instance:
(a + b).expensive();
However, in C 11 and above, returning values as non-const is strongly advised to take advantage of rvalue references, which only work with non-constant rvalues.
Therefore, while there was once a rationale for returning by const value, it has largely become obsolete in modern C . In summary, unless there are specific performance considerations or to prevent unintended bool casts (which can now be handled with explicit), returning values by const value is generally not considered preferable.
The above is the detailed content of When is Returning a Const Value in C Actually Beneficial?. For more information, please follow other related articles on the PHP Chinese website!