Whats wrong with this copy assignment cstor ?
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". I seem to be
getting my references and pointers mixed up. if (this) is a pointer,
what is it pointing to ?. I rember reading somewhere that the (this)
pointer points to the current instance of the class or the "live"
object). If this indeed the case, then I see no reason why I cannot
assign (this) to another valid pointer.
Could someone please point out the correct way to implement this cp
assignment cstor?. Tks
- Alfonzo Morra
4 Comments:
I found out (I think) why I can't assign to the this pointer, it's
because it's a const pointer. Hmmm ... so I can't call the copy
constructor as I'm doing above, I'll have to reproduce the cody in my
copy constructor ?
That dosen't sound very clean to me. I'm sure there must be a cleaner,
more OOP way of doing this ...
Even if the compiler lets you do the above it wouldn't work anyway. The
"this" pointer is a LOCAL variable and so changing its value has no effect
at all.
> 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.
Post a Comment
<< Home