title: C++ return by reference and return by const-reference value is copied
body: <p>I have some questions about returing a reference of a class member variable.</p>
  
  <p>I have the following code:</p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;set&gt;
  
  void
  PrintSet (const std::string &amp; str, const std::set&lt;uint32_t&gt; &amp; to_print)
  {
    std::cout &lt;&lt; str &lt;&lt; " (" &lt;&lt; to_print.size () &lt;&lt; "): ";
  
    for (std::set&lt;uint32_t&gt;::const_iterator it = to_print.begin ();
            it != to_print.end (); ++it)
      {
        std::cout &lt;&lt; *it &lt;&lt; " ";
      }
  
    std::cout &lt;&lt; "\n";
  }
  
  class Test
  {
  private:
    std::set&lt;uint32_t&gt; m_values;
  
  public:
  
    Test () : m_values () { }
  
    void
    SetValues (const std::set&lt;uint32_t&gt; &amp; values)
    {
      m_values = values;
    }
  
    const std::set&lt;uint32_t&gt; &amp;
    GetValues () const
    {
      return m_values;
    }
  
    std::set&lt;uint32_t&gt; &amp;
    GetValues ()
    {
      return m_values;
    }
  
    void
    Print () const
    {
      PrintSet ("TestInst", m_values);
    }
  };
  </code></pre>
  
  <ol>
  <li><p>I noticed that if I do this:</p>
  
  <pre><code>std::set&lt;uint32_t&gt; returned = test.GetValues ();
  </code></pre>
  
  <p>The variable <code>returned</code> gets a <em>copy</em>, not a reference, why?</p></li>
  <li><p>Does the <code>const std::set&lt;uint32_t&gt; &amp; GetValues () const</code> function <em>must</em> contain the double <code>const</code> (the one on the return value and the one after the function name) ?</p></li>
  </ol>
  
  <p>EDIT: Additional questions:</p>
  
  <ol start="3">
  <li><p>Knowing that <code>std::set&lt;uint32_t&gt; returned = test.GetValues ();</code> creates a copy. If I do this:</p>
  
  <pre><code>test.GetValues ().size ();
  </code></pre>
  
  <p>In order to call the <code>size ()</code> function (or any other member of the returned object), is a copy created temporarily or all is resolved with the returned reference?</p></li>
  <li><p>Is it bad to have three functions, return by value, by const-reference and by reference?</p>
  
  <pre><code>// Return by value
  std::set&lt;uint32_t&gt;
  GetValues () const
  {
    return m_values;
  }
  
  // Return by const-reference
  const std::set&lt;uint32_t&gt; &amp;
  GetValues () const
  {
    return m_values;
  }
  
  // Return by reference
  std::set&lt;uint32_t&gt; &amp;
  GetValues ()
  {
    return m_values;
  }
  </code></pre></li>
  </ol>