Re: another question about exception safety
On Mar 23, 10:23 pm, Mathias Gaunard <loufo...@gmail.com> wrote:
On Mar 24, 2:13 am, Mortiz <ydruga...@gmail.com> wrote:
Suppose some class has only two members: std::map<std::string,
std::string> member1 and std::string member2. Also it has ctor which
takes std::string and assigns it member2. In order to provide
exception-safe assignment operator for such class do I have to provide
non-throw swap method and use it inside assignment operator? How
should copy ctor look like
You can use the default copy constructor and assignment operator, they
will both be exception-safe.
Unfortunately no, the default assignment is not exception safe. The
default assigment assigns members and bases recursively. It doesn't
know how to revert if one of those operations throws. As a result, we
have a half-assigned object at hand.
There is no problem in the case of the default copy constructor,
because the object never ends up being half-constructed. (If any of
the member resources require explicit release, e.g. with delete, than
that's a separate issue that needs to be taken care of using RAII.)
We hear "the rule of the three", but we don't talk about "the rule of
the one" much. :) Regardless of the other two, the assigment operator
must be provided if we want strongly exception-safe assigment.
Ali
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]