Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding copying upon returning from a function - without relying on compiler optimizations
    text
    copied!<p>In this code, a huge vector <em>could be</em> (depending on compiler) copied upon return:</p> <pre><code>vector&lt;string&gt; foo() { vector&lt;string&gt; vec; //make vec huge return vec; } vector&lt;string&gt; bar = foo(); </code></pre> <p>How do I avoid copying the vector, <strong>without relying on compiler optimizations</strong>?</p> <p>Now, understand that this is just a simple example, with a single return statement. But for more complex cases, it is a possibility that even good compilers will not be able to do optimizations to avoid copying the vector. (<a href="https://stackoverflow.com/a/10479595/1859852">This answer</a> to another question mentions one such case.)</p> <p>(Relying on compiler optimizations always seemed rather strange to me in the first place, since I'm supposed to be writing <strong>good, portable, C++ code</strong>, as opposed to worrying about how this and that compiler does things under the hood. All those "compiler optimization" answers to the other questions therefore puzzle me.)</p> <p>One idea I came up with so far is to use C++11's smart pointers:</p> <pre><code>shared_ptr&lt;vector&lt;string&gt;&gt; foo() { shared_ptr&lt;vector&lt;string&gt;&gt; vec_ptr = make_shared&lt;vector&lt;string&gt;&gt;(); //make *vec_ptr (i.e. the actual vector) huge return vec_ptr; } shared_ptr&lt;vector&lt;string&gt;&gt; bar_ptr = foo(); //now, *bar_ptr is the underlying vector we can use </code></pre> <p>It looks like this will avoid the copy in all cases. The problem is that this code is getting to be quite cumbersome.</p> <p>Any good non-cumbersome alternatives? Supposedly, C++11 provides some new "move" functionality through rvalue references. Could those help?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload