
on 04.05.2010 at 19:36 Giovanni Piero Deretta wrote :
Then you haven't read the article carefully enough ;)
The idea is that rvalues passed to operator- (like in Peter's example) won't be copied due to elision of temporaries. Only lvalue parameters will be copied (you can't avoid that of course), while in your example you have an unconditional copy to initialize ret.
oh! now i get it the argument _must_ be passed by value for copy elision to be possible is that right?
what about idiomatic
return X().swap(x); //x is modified
my swap functions (and IIRC standard container swap functions) usually return void so it won't work in generic code, but if it works for your case, sure. Usually I refactor the pattern in a function like this:
template<typename T> T move_swap(T& x) { // T is default constructible and swappable T ret; using std::swap; swap(x, ret); return ret; }
So your operator- would look like this:
X operator- (X x) { modify x; return move_swap(x); }
you are absolutly right about swap() but that move_swap seems a truly perversion to me now ... however now i can find some logic under it -- Pavel P.S. if you notice a grammar mistake or weird phrasing in my message please point it out