Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 601
DLRdave Avatar asked Nov 12 '14 17:11

DLRdave


People also ask

Can we call destructor without constructor?

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.

Can an object call its own destructor?

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.

How do you call an object's destructor?

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(); };

Can you call a destructor in a constructor?

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.


1 Answers

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

like image 58
Deduplicator Avatar answered Nov 15 '22 01:11

Deduplicator