Re: ~ destructor doesn't destroy object?
On Dec 10, 12:04 am, muler <mulugeta.abe...@gmail.com> wrote:
#include <iostream>
class My_class {
public:
void print() const { std::cout << "alive and well!\n"; }
};
int main(int argc, char* argv[])
{
My_class mc;
// ..
mc.~My_class();
// mc is destroyed above, right? how come it come be used?
mc.print();
return 0;
}
+1 for Francis, this is horrible code.
Now for explanation: first, when object goes out of scope, it's
destructor is called automatically. So you should almost never write
code like the above.
Second, if you should not write such code, how come it's possible to
write it? Well, one more relevant use could be:
TYPE* p = new TYPE; // Object allocated on the heap.
// work work work
p->~TYPE(); // destroy object, but __preserve heap storage__
p = new (p) TYPE; // construct another object in same place
Why could this be relevant? Only if performance profiling pinpointed a
call to new as expensive. (But! That's very improbable anyhow, and
even less if new object is constructed immediately after ~TYPE,
because heap allocator, if it's any smart, will quickly find new free
heap slot - the one that was just "delete"-d).
When object is on stack, or embedded in (a member of) another object,
I know of no practical reason to call destructor explicitly.
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]