Is it possible to call a C++ object instance's destructor before its constructor?
Not that I actually want to do this, but I am wondering if it were to occur if it is definitely an indication of a compiler bug, or if there is a way for some errant C++ code to cause this obviously incorrect behavior (even if it's a contrived example).
I got to wondering about this when I noticed a pattern of measuring time in a time-logging constructor/destructor pair, and the code contained the implicit assumption: destructor time >= constructor time.
Presumably this assumption is always correct, given the same clock... And if violated, I would suspect a clock "problem" before suspecting a compiler bug.
So... is it possible? And if so, how?
Yes, the destructor is nothing more than a function. You can call it at any time. However, calling it without a matching constructor is a bad idea.
An explicit call to destructor is only necessary when an object is placed at a particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because the delete operator automatically calls destructor. Example: CPP.
A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example: class X { public: // Constructor for class X X(); // Destructor for class X ~X(); };
The more important question is should you call the destructor in the constructor and the answer is no. Destructors are automatically called for you and should never be called more than once. Therefore you should never call it yourself.
Yes, sure you can do that. It's only UB.
The simplest way is calling a dtor on a value whose lifetime you manage explicitly anyway:
union{std::vector<int> v;}; // This disables automatic dtor/ctor calls. Needs C++11
v.~vector<int>();
Calling a dtor before the ctor on an object is safe only if the ctor and/or the dtor is trivial (aka do-nothing).
Also known as, the object is always initialized.
I don't actually know of any reason to call the dtor but never/before the ctor.
Though it is possible to think of situations where you want to avoid calling either.
Anyway, you might want to be sure to use a monotonic clock-source, as e.g. local time (or the system clock) can and is adjusted backwards occassionally (DST, clock skew).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With