Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing temporaries as LValues
    primarykey
    data
    text
    <p>I'd like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:</p> <pre><code>vector&lt;T&gt; some_func() { ... return vector&lt;T&gt;( /* something */ ); } </code></pre> <p>Then, I would like to use</p> <pre><code>vector&lt;T&gt;&amp; some_reference; std::swap(some_reference, some_func()); </code></pre> <p>but <code>some_func</code> doesn't return a LValue. The above code makes sense, and I found this idiom very useful. However, it is non-standard. VC8 only emits a warning at the highest warning level, but I suspect other compilers may reject it.</p> <p><strong>My question is</strong>: Is there some way to achieve the very same thing I want to do (ie. construct a vector, assign to another, and destroy the old one) which is compliant (and does not use the assignment operator, see below) ?</p> <p>For classes I write, I usually implement assignment as</p> <pre><code>class T { T(T const&amp;); void swap(T&amp;); T&amp; operator=(T x) { this-&gt;swap(x); return *this; } }; </code></pre> <p>which takes advantage of copy elision, and solves my problem. For standard types however, I really would like to use <code>swap</code> since I don't want an useless copy of the temporary.</p> <p>And since I must use VC8 and produce standard C++, I don't want to hear about C++0x and its rvalue references.</p> <p>EDIT: Finally, I came up with</p> <pre><code>typedef &lt;typename T&gt; void assign(T &amp;x, T y) { std::swap(x, y); } </code></pre> <p>when I use lvalues, since the compiler is free to optimize the call to the copy constructor if y is temporary, and go with <code>std::swap</code> when I have lvalues. All the classes I use are "required" to implement a non-stupid version of <code>std::swap</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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