You are close. You need a swap so that your assignment operator looks like so:
struct my_object
{
my_object& operator=(my_object const& other)
{
my_object tmp(other);
swap(*this,other);
return *this;
}
};
You want your swap
to be nothrow
so that you have exception safety. Note that you can eliminate the name tmp
, and maybe allow some significant optimizations, if you just accept the parameter by value.
This is known as the "copy-swap idiom". There are numerous sources but it is best explained in Exceptional C++ by Sutter. He describes it in detail, some variations, and WHY it makes everything easier. When you pair it with pimpl you can gain a huge number of advantages...with some very minor effects on performance in most cases--sometimes it really matters and you can't do a pimpl (pointer indirection can confuse the prefetcher and such).
I don't know WTF Michael Roy is about. I have indeed seen crap like *this = other
in the copy constructor but every single dev that has done that also did a lot of other really stupid stuff that ended up giving headaches to way too many people. Just because something is done by some people doesn't mean you need to follow them off a cliff into nonsense.