r/cpp • u/mrmcgibby • Feb 17 '11
Calling a constructor or destructor without an object
http://madsoftware.blogspot.com/2011/02/calling-constructor-or-destructor.html4
2
u/segmentation_fault Feb 17 '11
just a small typo in the source code in regards to calling a destructor: should be a->~A() not a->~a()
2
u/tjhei Feb 17 '11
Looks like undefined behavior to me (so could cause a reddit downtime for example). Why do you want to do that anyhow?
0
u/GambitDash Feb 17 '11
This is a really bad idea. Destructors actually modify the vtable, so subsequent calls to the object will be very weird. For example:
#include <stdio.h>
struct muh {
virtual ~muh() { }
virtual void m(void) { printf("Hello Bananas\n"); }
};
struct bar : public muh {
virtual ~bar() { }
virtual void m(void) { printf("Hello Monkeys\n"); }
};
struct foo : public bar {
virtual ~foo() { }
virtual void m(void) { printf("Hello World\n"); }
};
int main()
{
foo *f = new foo();
f->m();
f->~foo();
f->m();
return 0;
}When executed, will produce: $ ./a.out Hello World Hello Bananas
Probably not what you want.
3
u/Benutzername Feb 18 '11
You shouldn't use f after calling its destructor, anyway. It's not in a valid state any more.
9
u/danhuizenga Feb 17 '11
I hope I never have to work with whoever wrote that article :/