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:
free()
)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)Thank you in advance.
C++ is a bit misleading here:
Construction and memory management are actually completely unrelated processes which C++ munges together in new
and delete
for convenience.
However, C++ doesn’t actually have a dedicated syntax to call a constructor on existing memory – to do this, you need to use the “placement new
” syntax which actually is not a conventional new
at all – i.e., it doesn’t allocate memory.
On the other hand, there is a syntax to call the destructor of an object. And your code uses it correctly. And no, using delete
would not be equivalent, it would free memory in addition to calling a destructor.
Compare this with the std::allocator
class, which has the methods (and their corresponding semantics)
allocate
(== ::operator new(sizeof T)
)deallocate
(== ::operator delete(&x)
)construct
(== new (&x) T()
)destroy
(== x.~T()
)These correspond precisely to the different aspects of an object’s lifetime cycle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With