Reputation: 345
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?
Upvotes: 9
Views: 10751
Reputation: 5397
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.
Upvotes: 3
Reputation: 11
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)...
Upvotes: 1
Reputation: 88027
object.~TYPE()
and object.~TYPE::TYPE()
are both correct I think. Sounds a bit dubious however, what are you trying to achieve?
Upvotes: 1
Reputation: 258678
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();
Upvotes: 8