Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Constness of a member function should be decided based on the question: <strong>is the member function used in a context to modify the object?</strong> (either the member modifies the object directly, or returns a reference/pointer to internal data so that outside callers can modify the object). If yes, make it non-const, otherwise make it const. </p> <p>The compiler will correctly choose between overloads that differ on constness alone. However, <strong>the return type is not used in overload resolution.</strong> Furthermore, the return by-value/by-reference should be decided only on the expected cost and the intended ownership of what you are going to return. Fortunately, C++11 makes life easier by providing <a href="https://stackoverflow.com/questions/3106110/what-are-move-semantics">move semantics</a>. This means that you can happily return large data structures by-value. Only return by reference if the referenced object will outlive the outside caller. </p> <p>It seems to me that your <code>int&amp; get()</code> should be renamed <code>void set(int)</code> and that you could split your <code>int get() const</code> into a computation helper and a proper <code>get()</code></p> <pre><code>class C { int val_; public: void modify() { /* some expensive computation on val_ */ } int get() const { return val_; } void set(int v) { val_ = v_; } }; </code></pre> <p>Alternatively, if you want to keep to <code>get()</code> functions, you could do</p> <pre><code>class D { int val_; public: void modify() { /* some expensive computation on val_ */ } int get() const { modify(); return val_; } int&amp; get() { modify(); return val_; } // no const-cast needed }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload