Re: c++ faq 16.22 reference counting
Vladimir Jovic wrote:
Hello,
Reading 16.22 in c++ faq, I wondered why the assign operator wasn't
implemented like this :
FredPtr& operator= (FredPtr const& p)
{
FredPtr tmp( p );
std::swap( tmp, *this );
Here, you want to use a swap function provided by the FredPtr class:
std::swap() would rely on operator= triggering an infinite loop.
return *this;
}
The effect should be the same. tmp goes out of scope, and old object is
destroyed (count is decreated, and old object deleted if count=0), and
new object is copy constructed, therefore the count is increased by 1.
Is this correct, or am I missing something?
You are correct. I think, this particular FAQ item was written before the
copy-swap idiom became fashionable. The reference counting example nicely
illustrates one of the strong points of the copy-swap idiom: it separates
concerns into construction, destruction, and swapping internals.
Implementing the assignment operator from scratch makes one think about the
proper order of operations, and it is not so trivial to get it right.
Best
Kai-Uwe Bux