Destructor call

I have a class where I overload new ones and delete (they retrieve and return memory from the memory pool and to the memory pool). It frustrates me that the class on which I am overloaded still has its destructor, called before the called overload function is called. How can i stop this?

class Message { ~Message() { ... } void* operator new(std::size_t sz) { ... } void operator delete(void* ptr) { ... } }; 

EDIT:

That's right, thinking that class members will be destroyed, but memory will not be freed by destructors; the delete function owns this responsibility, in which case can I stop the freeing of memory?

RESULT: Penny discarded that allocating / freeing memory and building / destroying are separate elements. Now I have empty destructors and overloaded new / delete.

+6
c ++
source share
4 answers

Destruction and de-distribution are two orthogonal things; the other cannot be forbidden. What would you do with instances of your class that were created on the stack? Do not clean your resources? You are trying to break up the very useful concept of RAII .

+6
source share

I don’t think you can prevent the destructor from being called, and I’m not sure why you need it. An object must be destroyed before the memory is freed - if the superclass assigned some resources, its destructor must free them before the memory is freed.

Edit after editing: Yes, destructors clear everything that they allocate, but do not free up object memory. The delete method you write does this.

By the way, a beautiful name. :-)

+4
source share

If you are concerned about (a) capturing memory from a specific pool and (b) managing when destructors are called as one of the options, placing a new

 void* raw = allocate(sizeof(Foo)); // line 1 Foo* p = new(raw) Foo(); // line 2 p->~Foo(); // explicitely call destructor 

(code taken from the above link to frequently asked questions on C ++)

+3
source share

Answering your question, yes, constructors and destructors are called if you are overloading new / deleting or not.

When answering a question that you did not ask, be it a good solution for using objects with a memory pool, the answer is usually no. What you want is your classes working with the memory pool to take the allocator class. This allows you to significantly increase flexibility, and usually you have more than one class, but many of them will be placed in the memory pool, so you do not want to have a massive overload of all new / deleted functions. In addition, it is not unusual to have multiple layouts (and therefore distributors), but you can overload new / delete only once.

0
source share

All Articles