title: Is there a right way to return a new object instance by reference in C++?
body: <p>So I was writing some code, and I had something like this:</p>
  
  <pre><code>class Box
  {
      private:
      float x, y, w, h;
  
      public:
      //...
      Rectangle &amp; GetRect( void ) const
      {
          return Rectangle( x, y, w, h );
      }
  };
  </code></pre>
  
  <p>Then later in some code:</p>
  
  <pre><code>Rectangle rect = theBox.GetRect();
  </code></pre>
  
  <p>Which worked in my debug build, but in release there were "issues" returning that Rectangle by reference -- I basically got an uninitialized rectangle. The Rectangle class has an = operator and a copy constructor. Without getting into why this broke, I'm actually more interested in the correct way to return a (new) object by reference <b>for the purpose of <s>assigning</s> copying to a variable.</b> Am I just being silly? Should it not be done? I know I can return a pointer and then dereference on assignment, but I'd rather not. Some part of me feels like returning by value would result in redundant copying of the object -- does the compiler figure that out and optimize it? </p>
  
  <p>It seems like a trivial question. I feel almost embarrassed I don't know this after many years of C++ coding so hopefully someone can clear this up for me. :)</p>