DLRdave
DLRdave

Reputation: 14280

Is it possible to call a C++ object instance's destructor before its constructor? If so, how?

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?

Upvotes: 5

Views: 126

Answers (2)

Deduplicator
Deduplicator

Reputation: 45704

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).

Upvotes: 5

Slava
Slava

Reputation: 44278

Yes technically it is possible to write such code. But I believe you are really asking "would somebody do it"? I cannot imagine a situation when such situation would be necessary. So I think you can expect that this should not happen in properly written program, but keep in mind that it is possible to meet such situation (you may decide to produce diagnostics in such case).

Upvotes: 1

Related Questions