title: How can I ensure RVO instead of copy is performed?
body: <p>In many cases, I would like to create a new instance of data and return it to the API caller. </p>
  
  <p>I learned that <code>unique_ptr</code>/<code>shared_ptr</code> can be used for factory pattern (for example, <a href="https://stackoverflow.com/questions/27282453/factory-pattern-using-unique-ptr-in-c">Factory pattern using unique_ptr in c++</a>)</p>
  
  <p>At the same time, I learned that returned value optimization (RVO) is possible in many compilers (for example, <a href="https://stackoverflow.com/questions/15704565/efficient-way-to-return-a-stdvector-in-c">Efficient way to return a std::vector in c++</a>). </p>
  
  <p>I prefer RVO since it is easier to use the returned value without a wrapping <code>unique_ptr</code> and easier to read the code, however, since the RVO is not guaranteed, I don't want to sacrifice performance unexpectedly and have to use <code>unique_ptr</code> to ensure returned value is <code>move</code>d instead of copied. </p>
  
  <p>Is there any approach that I can explicitly specify the return value to be moved, so that either it will not complain anything if RVO is possible or it will trigger some compiler warning if RVO is not possible? If this is possible, I can safely get rid of returning a unique_ptr in this case.</p>
  
  <p>I am using C++17 and need to support Apple Clang 11.0 on macOS and g++ 9 on Linux.</p>
  
  <p><strong>Edited:</strong></p>
  
  <p>I am still learning C++ and didn't make distinction between RVO (Return Value Optimization) and NRVO (Named Return Value Optimization) when posting this question. It seems to me NRVO is more common and useful in patterns like factory method, for example:</p>
  
  <pre><code>vector&lt;foo&gt; vec;
  // populate data into vec
  return vec;
  </code></pre>
  
  <p>And I am looking for something like a <code>return std::move_only(returned_value)</code> that will give me a compiler warning if this value cannot be moved (not copy to move).
  Maybe I should re-phrase my question as: if NRVO is not guaranteed, why "return by value" is still the recommended way in this question (<a href="https://stackoverflow.com/questions/15704565/efficient-way-to-return-a-stdvector-in-c">Efficient way to return a std::vector in c++</a>), shouldn't the answer be "it depends" on your function implementation and whether or not you could accept unexpected performance cost?</p>