|
Boost Users : |
From: Johan Ericsson (johanericsson_at_[hidden])
Date: 2002-01-17 10:56:37
> House& House::operator =(const House& source)
> {
> assert(m_rooms == -1);
> this->~House();
> new(this) House(source);
> return *this;
> }
I looked at the C++ FAQ and I was surprised not to
find this mentioned in there. This "technique" is
generally regarded as poor technique and potentially
dangerous by the "gurus".
It is not exception safe: If the copy constructor
fails due to an exception, then the "this" object will
be left in a destroyed state. It will probably be
destroyed again when your object leaves scope.
Destroying an object twice is undefined behavior.
If you derive off of your "house" object, then this
assignment operator will slice any of the derived
parts...
In general, assignment operator should look like this
(WARNING: untested code)
House& House::operator =(const House& source)
{
House temp(source);
Swap(temp);
return *this;
}
The Swap() function is a member function that has
"No-Throw" specification. It swaps out the internals
of the *this instance with the "temp" instance.
Using this method, you are still writing your
assignment operator in terms of your copy constructor,
so you don't need to duplicate work. And this method
is strongly exception safe; if the copy constructor
throws, then the current object is unchanged.
Also, I would recommend that you either reconsider
having the constant member variable, or use a
vector<>.
Johan
__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net