In message <11*********************@f14g2000cwb.googlegroups. com>, Old
Wolf <ol*****@inspire.net.nz> writes
Alfonzo Morra wrote: I've the ff code in cp assignmenent cstor:
PB& PB::operator=( const PB& b) {
if ( this != &b ) {
PB *pb = new PB( b ) ;
this = pb ; // <- Compiler barfs here
}
return *this ;
}
The error msg is : "'=' : left operand must be l-value".
You can't assign to 'this'. Objects cannot change their
address. (You can move an object, but that's not what's
going on here).
Imagine what would happen here, if objects could change address:
void foo()
{
PB pb, qb;
pb = qb;
}
When the function ends, the compiler will destroy pb. But if
your operator= has relocated the object to a new address, the
compiler will delete the old address.
Could someone please point out the correct way to implement this cp
assignment cstor?
It looks like implementing it in terms of the copy-constructor
isn't going to work. One solution is to move your code from the
copy-constructor to the assignment-operator, and then you can
have the copy-constructor call the assignment-operator.
But the assignment operator has (in principle) to deal with deleting the
old values before assigning the new ones, which the copy constructor
doesn't. That can cause complications.
It's often better to write a swap() function and then use the
copy-and-swap idiom to implement the assignment operator in terms of the
copy constructor.
PB & PB::operator=(PB const & a)
{
PB(a).swap(*this);
return *this;
}
so the temporary's destructor will deal with deleting the old values.
--
Richard Herring