Re: return string - no double allocation
* Gernot Frisch:
Design: it's generally a bad idea to implement a copy constructor in
terms of assignment. Instead implement assignment in terms of copy
construction.
How can that be done?
DGStr operator=(const DGStr& s)
{
*this(s);
return *this;
}
so?
Almost. The most common is the 'swap' idiom.
DGStr& operator=( DGStr other )
{
swap( other );
return *this;
}
where 'swap' is a member function that guarantees to swap the contents of *this
with that of the specified DGStr, in constant time, without throwing.
Here the pass-by-value is intentional: the copy is constructed at the call site,
and after the swapping that copy's destructor takes care of deallocating the old
value.
std::swap comes in handy for implementing swap.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!