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

I have several classes that I connected to AngelScript . This engine uses an interesting way to allocate objects: it allocates the necessary amount of memory (possibly with malloc() ), and when the authors propose using this construction to create an object in this memory:

 static void Constructor(ObjectType *thisPointer) { new(thisPointer) ObjectType(); } 

and code like this to destroy an object:

 static void Destructor(ObjectType *thisPointer) { thisPointer->~ObjectType(); } 

I have a few questions:

  • Is it correct to use a destructor? (Eclipse judges this as an error) As I understand it, this code should call the destructor without freeing up memory (calling free() )
  • Is it possible to use delete(thisPointer) (or something like this) instead of this construct and will it be equivalent? (at least this code gives no errors at compile time and runtime)
  • Are there other ways to call the destructor without freeing up memory?

Thanks in advance.

+6
source share
2 answers

Is it correct to use a destructor?

Yes. You built the object in place using place-new, and therefore you need to destroy it with an explicit call to the destructor (provided that it has a non-trivial destructor).

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

Not. delete will try to use operator delete() to free memory in free storage; this is true only if it was assigned the normal expression new (or, perhaps, the explicit use of operator new() ).

Are there other ways to call the destructor without freeing up memory?

Not really. Calling the destructor is by far the clearest and easiest way to call the destructor.

+5
source

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.

+12
source

Source: https://habr.com/ru/post/916561/


All Articles