Should I Return const Objects or Pointers?
In "Effective C Item 03", it is recommended to utilize const whenever feasible. For example, a Bigint class could have both a mutable and a const version of an operator[] function to access its data.
However, the distinction between returning a const object and returning a non-const object is less clear for simple functions like foo() that return primitive types. One might assume they behave identically, but this is not entirely true.
Top-Level cv-Qualifiers and Return Types
In the case of primitive types, top-level cv-qualifiers on return types are disregarded. Therefore, the following function declarations are functionally equivalent:
<code class="cpp">int foo(); int const foo();</code>
Both functions return an int, regardless of the const qualifier on the return type.
The Significance for Class Types and References
The distinction becomes crucial when dealing with class types or references. Returning a const T prevents the caller from invoking non-const member functions on the returned value. Consider the following example:
<code class="cpp">class Test { public: void f(); void g() const; }; Test ff(); Test const gg(); ff().f(); // legal ff().g(); // legal gg().f(); // illegal gg().g(); // legal</code>
Here, gg() returns a const Test object, which prohibits calling its non-const member function f().
The above is the detailed content of When Should I Return const Objects or Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!