Re: how to reuse a copy constructor in an operator = function
My associate has written a copy constructor for a class. Now I need to a=
dd
an operator = to the class. Is there a way to do it without change her=
code
(copy constructor) at all? Your help is much appreciated.
There is simpy no need to alter the copy constructor at all. Plain and
simply write an operator= to the class. But I realize, because of the
title of the post, that your question is not quite that. You actually
would like to reuse the copy constructor inside operator=.
I see no solution other than copying the constructor code (if you do
have acces to that) as a help to begin writing operator=. Whether this
falls under the "code reusing" category may be discussed.
Another solution I see, would be to provide an efficient swap() member
to your class and use the copy constructor like this:
class MyClass {
public:
MyClass( const MyClass& ); //Copy constructor
swap( MyClass& ); //Swap the content of two opbjects.
//This can be done rather efficiently by swapping only
//pointers and references to deep content.
MyClass& operator=( const MyClass& ); //See below.
};
MyClass& MyClass::operator=( const MyClass& rhs )
{
MyClass temp( rhs ); //Reusing copy constructor code.
this->swap( temp );
return( *this );
}
Notice that this may be sub-optimal because some instructions in the
copy constructor will be much the same than some in the swap() method.
If one could assign to the this pointer, things could be made easier,
even without that swap() method.
This raises the question: why isn't the this pointer a valid lvalue?
Elias Salom=E3o Helou neto.