Re: avoiding temporaries
Gene Bushuyev wrote:
"Marek Vondrak" <none@none.com> wrote in message
news:e776rl$f7l$1@ns.felk.cvut.cz...
Dear group,
I would like to ask if the following code is legal C++ and
whether NRVO optimization is applicable at operator=().
Consider the following example:
[...]
Vector operator=( const Vector & v )
{
this->~Vector();
new( this ) Vector( v ); // [1]
}
This implementation is terrible for so many reasons. Herb
Sutter spent 8 pages explaining why (see Exceptional C++, 41).
Moreover, it won't compile as the function is missing return
statement, and assignment operator normally returns reference,
not copy. So in this case a good solution should be something
like this:
Vector& operator = (Vector v)
{
v.swap(*this);
return *this;
}
Isn't this a bit overkill for his class. A class which consists
of only basic types, and thus cannot possibly throw anything,
ever. In such cases, simply copying does the trick nicely.
--
James Kanze GABI Software
Conseils en informatique orient��e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S��mard, 78210 St.-Cyr-l'��cole,
France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]