title: C++ const-reference semantics?
body: <p>Consider the sample application below. It demonstrates what I would call a flawed class design.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  struct B
  {
   B() : m_value(1) {}
  
   long m_value;
  };
  
  struct A
  {
   const B&amp; GetB() const { return m_B; }
  
   void Foo(const B &amp;b)
   {
    // assert(this != &amp;b);
    m_B.m_value += b.m_value;
    m_B.m_value += b.m_value;
   }
  
  protected:
   B m_B;
  };
  
  int main(int argc, char* argv[])
  {
   A a;
  
   cout &lt;&lt; "Original value: " &lt;&lt; a.GetB().m_value &lt;&lt; endl;
  
   cout &lt;&lt; "Expected value: 3" &lt;&lt; endl;
   a.Foo(a.GetB());
  
   cout &lt;&lt; "Actual value: " &lt;&lt; a.GetB().m_value &lt;&lt; endl;
  
   return 0;
  }
  </code></pre>
  
  <p><strong>Output:</strong><br>
  Original value: 1<br>
  Expected value: 3<br>
  Actual value: 4<br><br></p>
  
  <p>Obviously, the programmer is fooled by the constness of <code>b</code>. By mistake <code>b</code> points to <code>this</code>, which yields the undesired behavior.</p>
  
  <p><strong>My question:</strong> What const-rules should you follow when designing getters/setters?</p>
  
  <p>My suggestion: Never return a reference to a member variable if it can be set by reference through a member function. Hence, either return by value <strong>or</strong> pass parameters by value. (Modern compilers will optimize away the extra copy anyway.)</p>