Re: how to reuse a copy constructor in an operator = function
Andrew Koenig wrote:
"Kai-Uwe Bux" <jkherciueh@gmx.net> wrote in message
news:fgii3a$mpu$1@murdoch.acc.Virginia.EDU...
It also causes no end of problems if someone inherits from the
class.
(a) That's one of the gotchas, and
(b) the reason for using
this->T::~T();
instead of
this->~T();
That actually takes care of _many_ problems this method can cause in the
context of inheritance.
Well yes, but it misses the most important problem.
Suppose you derive from T, and write an assignment operator in the derived
class that calls the one from the base class:
class T1: public T {
// ...
T1& operator=(coust T1& x) {
this->T::operator=(x);
// Do some other stuff here
return *this;
}
// ...
};
When T1::operator= calls T::operator=, T::operator= will stealthily
destroy the object, which had dynamic type T1, and replace it with a new
object that
has dynamic type T. Of course, the compiler won't know about this for the
purpose of static type checking.
The result will be chaos.
I think, that would happen if you did this->~T(). The version this->T::~T()
does not call the derived destructor:
#include <iostream>
struct X {
virtual
~ X ( void ) {
std::cout << "destroying X\n";
}
X & operator= ( X const & other ) {
if ( this != &other ) {
this->X::~X();
new (this) X (other);
}
return ( *this );
}
};
struct Y : public X {
~ Y ( void ) {
std::cout << "destroying Y\n";
}
Y & operator= ( Y const & other ) {
X::operator=( other );
return (*this );
}
};
int main ( void ) {
Y* a_ptr = new Y;
Y* b_ptr = new Y;
*a_ptr = *b_ptr;
// intentionally leaking so that the Y-destructor remain silent
}
On my machine, this prints just "destroying X". Now, of course, if you are
right, then this program probably has undefined behavior; but I think, it's
well-defined and does not destroy any Y objects in the assignment.
Best
Kai-Uwe Bux