Home >Backend Development >C++ >When is Returning a Const Value in C Actually Beneficial?

When is Returning a Const Value in C Actually Beneficial?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 15:49:10960browse

When is Returning a Const Value in C   Actually Beneficial?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn