C ++ is a bit misleading:
Design and memory management are actually completely unrelated processes that C ++ combines in new
and delete
for convenience.
However, C ++ does not have a special syntax for calling a constructor in existing memory - for this you need to use the syntax "placing new
", which is actually not ordinary new
at all, i.e. he does not allocate memory.
On the other hand, there is syntax for calling an object's destructor. And your code uses it correctly. And no, using delete
will not be equivalent; it will free up memory in addition to calling the destructor.
Compare this to the std::allocator
class, which has methods (and their corresponding semantics)
allocate
(== ::operator new(sizeof T)
)deallocate
(== ::operator delete(&x)
)construct
(== new (&x) T()
)destroy
(== x.~T()
)
They exactly correspond to various aspects of the life cycle of objects.
source share