Re: Is it a good idea to implement constructors with assignment operator?
On Aug 3, 9:16 am, Weihui Shen <swl...@gmail.com> wrote:
On 8 3 , 2 40 , "BobR" <removeBadB...@worldnet.att.net> wrote:
Weihui Shen <swl...@gmail.com> wrote in message...
Hello. Sometimes I see that some class constructors were implemented
with assignment operator and I wanna know whether it is safe to do
that or not?
[...]
Please consider the following code:
class A {
public:
A(int a) {
*this = a; // call A::operator=(int), it's safe?
}
A& operator =(int b) {
a = b;
return *this;
}
private:
int a;
};
I mean that calling A's assignment operator in A's constructor.
As a general rule, no. In general, an assignment operator can
only be called on a fully constructed object.
The usual idiom, in fact, is the reverse: use the copy
constructor to implement assignment. This is often associated
with a shallow swap, to give something like:
A&
A::operator=(
A const& other )
{
A tmp( other ) ;
tmp.swap( *this ) ; // but ONLY if swap is shallow!!!
return *this ;
}
The idea, of course, is that any operations that might fail will
have taken place before any modification to the object.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34