title: C++ Question About Return Value Optimization
body: <p>There are many questions on this site about return value optimization (I suppose it's a fairly confusing topic), but I can't seem to find one that answers my particular question.  If I have code that looks like this:</p>
  
  <pre><code>returnType function() { stuff....}
  
  void someOtherFunction()
  {
      returnType var = function();
      more stuff...
  }
  </code></pre>
  
  <p>I am told that the compiler may decide to not use two instances of <code>returnType</code> in <code>someOtherFunction()</code>.  Logically, I would expect that <code>function()</code> would generate an object of type <code>returnType</code>, and <code>someOtherFunction()</code> would receive that value via copy constructor (overloaded or not) into a temporary value.  I would then expect that temporary value to be copied via assignment (which could be overloaded and in theory could have any kind of functionality!) into <code>var</code>, which would have previously been initialized via the default constructor.  </p>
  
  <p>I see a potential issue here.  What happens if there is not this temporary copy of <code>returnType</code> in <code>someOtherFunction()</code>?  Wouldn't <code>var</code> have to be filled, via copy constructor, with the returned value from <code>function()</code> directly?  If so, wouldn't the assignment operator never be called?  If so, and if the assignment operator were overloaded, couldn't that change the functionality of the program?  If so, does that mean that it's the programmer's responsibility to ensure that <code>=</code> always does the same thing as a copy constructor?  And I hate to run this long chain of questions, but if so, why does C++ allow you to define copy constructors to do something other than assignment?</p>