title: How can a function in C++ return either a value or a reference with minimal copying?
body: <p>I have a function that delegates to two others, returning either a reference or value depending on some runtime condition:</p>
  
  <pre><code>X by_value() { ... }
  const X&amp; by_reference() { ... }
  
  ?? foo(bool b) {
    if (b) {
      return by_value();
    } else {
      return by_reference();
    }
  }
  </code></pre>
  
  <p>I'd like to choose the return type of my function so that callers induce minimal copying; e.g.:</p>
  
  <pre><code>const X&amp; x1 = foo(true);   // No copies
  const X&amp; x2 = foo(false);  // No copies
  X x3 = foo(true);          // No copies, one move (or zero via RVO)
  X x4 = foo(false);         // One copy
  </code></pre>
  
  <p>In all cases except the last, there shouldn't be a need (based on the <em>runtime</em> behavior) to copy the return value.</p>
  
  <p>If the return type of <code>foo</code> is <code>X</code>, then there will be an extra copy in case 2; but if the return type is <code>const X&amp;</code>, then cases 1 and 3 are undefined behavior.</p>
  
  <p>Is it possible, via returning some sort of proxy, to ensure that the above uses have minimal copies?</p>
  
  <hr>
  
  <p><strong>Explanation</strong>: Since there's been significant pushback of the form "you're doing it wrong", I thought I'd explain the reason for this.</p>
  
  <p>Imagine I have an array of type <code>T or function&lt;T()&gt;</code> (meaning the elements of this array are either of type <code>T</code>, or they're functions returning <code>T</code>). By the "value" of an element of this array, I mean, either the value itself or the return value when the function is evaluated.</p>
  
  <p>If this <code>get_value_of_array(int index)</code> returns by value, then in the cases where the array contains just an element, I'm forced to do an extra copy. This is what I'm trying to avoid.</p>
  
  <hr>
  
  <p><strong>Further note</strong>: If the answer is, "That's impossible", that's fine with me. I'd love to see a proof of this, though - ideally of the form "Suppose there were a type <code>Proxy&lt;X&gt;</code> that solved your problem. Then...`</p>