开发者

C++ destructor: when the memory gets freed?

开发者 https://www.devze.com 2023-02-06 09:40 出处:网络
If I delete an object which causes its destructor to be called, does the memory get freed before or after the destructor has finished doing whatever there is in 开发者_运维问答the function?Memory is o

If I delete an object which causes its destructor to be called, does the memory get freed before or after the destructor has finished doing whatever there is in 开发者_运维问答the function?


Memory is only freed once the least derived class subobject has been destroyed. So if you have:

class Base {
};

class Derived : public Base {
public:
    ~Derived();
};

then first Derived is destroyed, then Base is destroyed and only then memory is deallocated.


Decompose delete into what it is actually doing and it is relatively clear to see when the memory is deleted. So a statement like this:

delete some_ptr;

Is roughly equivalent to this pseudo-code:

some_ptr->~some_ptr();
free( some_ptr );

So the memory is freed after the call to the destructor. Exactly what the destructor does is not determined by the delete operator, but rather the definition of the class. Usually it does local cleanup and ensures that its base class destructors are also called.

It is important to realize that freeing the memory is not actually part of the destructor. It is the delete operator which frees the memory.


Note that the free function in pseudo-code is actually one of the operator delete() functions, either for the deleted class, or global. That actually frees up the memory.


The memory gets freed after the destructor has finished. Otherwise, accessing member variables inside the destructor would cause segfaults.


operator delete is called after destructor, but when the memory is freed is up to used allocator


I would think that the memory is freed after the destructor function itself has finished executing. I know that when an exception is caught, the destructor to the object is not called until the object itself goes out of scope.


In C++, destruction is about executing some code using the data available in the object. This code is arbitrary.

Free'ing the memory is a low level handling, hidden by the delete operator in general, that should never be called prior to calls to the destructor.

This is best summarized by the Allocator interface:

  • allocate and deallocate are used to manipulate raw memory
  • construct and destroy are used to call the constructors and destructors of the objects

It is precised that construct, destroy and deallocate should only be executed on memory previously allocated by that allocator. It also precises that destroy does not deallocate the memory, and that a subsequent call to deallocate will be necessary.

Note that this is a low-level interface, which allow destroying an object and reusing the freed space to construct another in place.

0

精彩评论

暂无评论...
验证码 换一张
取 消