Is delete(Object) equivalent to calling Object.~Object()

c++, memory

Solution

Is it correct way to use destructor this way?

Yes. You constructed the object in-place using placement-new, and so it must be destroyed with an explicit destructor call (assuming it has a non-trivial destructor).

Is it possible to use `delete(thisPointer)` (or something like it) instead of this construction and is it will be equivalent?

No. `delete` will attempt to use `operator delete()` to release the memory to the free store; this is only valid if it was allocated with a normal `new` expression (or perhaps an explicit use of `operator new()`).

Is there other ways to call destructor without deallocating memory?

Not really. Calling the destructor is certainly the clearest and simplest way to call the destructor.

Problem

I have several classes which I connected to AngelScript engine. This engine uses interesting way to allocate objects: It allocates needed amount of memory (possibly with `malloc()`) and when authors propose to use construction like this to create object in this memory: ``` static void Constructor(ObjectType *thisPointer) { new(thisPointer) ObjectType(); } ``` and code like this to destroy object: ``` static void Destructor(ObjectType *thisPointer) { thisPointer->~ObjectType(); } ``` I have several questions: - Is it correct way to use destructor this way? (Eclipse judges this as a bug) As far as I can understand this code should call destructor without deallocating memory (calling `free()`) - Is it possible to use `delete(thisPointer)` (or something like it) instead of this construction and is it will be equivalent? (at least this code gives no errors during compilation and runtime) - Is there other ways to call destructor without deallocating memory? Thank you in advance.

Original source