c++ - Why doesn't default assignment operator call the destructor first? -


so in following example, cause class foo replace *this = foo(). i'm glad tested because turns out in circumstance, destructor of old foo doesn't called. guess that's because default assignment operator uses memcpy ... language design question ... why wouldn't make default assignment operator destroy assigned-to object first prevent accidents?

http://codepad.org/9wco6yz5

#include <iostream> using namespace std;  class mustbedestroyed //(for reason not shown here) { public:   int i;   mustbedestroyed(int i) : i(i) {}   ~mustbedestroyed() { cout << "destroyed contained class " << << endl; } };  class foo { public:   mustbedestroyed x;   foo(int y) : x(y) {}   void replace_myself(int y) { foo f(y); *this=f; }   void print() { cout << "this outer/inner class " << x.i << endl; }   ~foo() { cout << "destroyed outer class " << x.i << endl; } };  int main() {   foo a(1);   a.print();   a.replace_myself(2);   a.print();   return 0; } 

why assignment call destructor? says does: calls assignment operator. compiler generated assignment operator obvious: assignment of members old obejct new (using assignment operation). nothing more, nothing less. reason famous rule of three.

now why doesn't call destructor: end lifetime of object. while theoretically possibly construct new object inplace of old one, approach typically incorrect in face of exception (look @ question more that), can't used in general case. besides if did approach proposed, wouldn't call assignment operators members, destructor/copy constructor instead. means custom assignment behaviour (which doesn't need same copy behaviour) not honored.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -