Question

For example, we have a function like that:

template <typename TYPE>
void construct_and_destruct(TYPE & object)
{
    //...
}

We cant call constructor and destructor like object.Type() and object.~Type() (no true now) ( Whyy? =C )

To call the constructor we can like new(&object) TYPE(). And I dont know how to call destructor (no exist placement delete). How to do this?

Was it helpful?

Solution

You can call the destructor as:

object.~TYPE();

but it's likely not what you want, and are subject to a double delete.

The constructor is as simple as:

object = TYPE();

OTHER TIPS

object.~TYPE() and object.~TYPE::TYPE() are both correct I think. Sounds a bit dubious however, what are you trying to achieve?

Try this Calling destructor with decltype and\or std::remove_reference, it worked for me to call the destructor of an unqualified type (unspecified inner class inside a template argument)...

I came at this with a slightly different problem, but also for placement-new/delete, and the solution should be similar.

Given a dependent type name the placement new:

new (&foo) typename AT::T(arg, arg, arg);

The associated delete is tricky:

foo.~ typename AT::T();  // Doesn't work, nor do variations of syntax

The modern solution seems to be std::destroy_at(&foo) but my compiler doesnt have full C++17. Rolling a basic version of your own isn't difficult however:

template <typename T>
constexpr void destroy_at(T* p)
{
  p->~T();
}

Seems fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top