Volker Weißmann
Volker Weißmann

Reputation: 574

Destructing objects with private destructors

I'm currently working on a program that generates C++ code. This generated C++ code sometimes needs to destruct a Class, so it uses

ptr->~MyClass();

, because this works in all corner cases (including for example inherited destructors). Or so I thought: If there is a private destructor:

class MyClass {
    ~MyClass();
};

Then ptr->~MyClass(); will be a compile time error.

Any ideas what I could do? If the destructor is private, the generated code should either call it anyway or throw an exception or exit the program.

Note that my code generatator does not know which class has a private destructor and which class does not have a private destructor.

Upvotes: 0

Views: 56

Answers (2)

Jarod42
Jarod42

Reputation: 217283

You could use SFINAE:

template <typename T>
auto destruct(T* t) -> decltype(t->~T()) { t->~T(); }

auto destruct(void*) { /*  throw, exit, ... */ }

Demo

Upvotes: 3

andrei81
andrei81

Reputation: 68

You should prefer not to call the destructor explicitly! It's called automatically when the object goes out of scope.

Upvotes: 0

Related Questions