问题描述:

I have a class on which I am overloading new and delete (these fetch and return memory from and to a memory pool). What's frustrating me is that the class on which I have overloaded still has it's destructor called before the delete overloaded function get's called. How can I stop this?

class Message

{

~Message() { ... }

void* operator new(std::size_t sz) { ... }

void operator delete(void* ptr) { ... }

};

EDIT:

Am correct in thinking that the members of the class will be destructed but the memory won't be freed by the destructors; the delete function owns this responsiblity in which case I can stop the memory from being deallocated?

OUTCOME:

Penny dropped that the allocation/deallocation of memory and construction/destruction are separate items. I now have empty destructors and overloaded new/delete.

网友答案:

Destruction and de-allocation are two orthogonal things, one should not inhibit the other. What would you do with instances of your class that were created on the stack? Not cleanup their resources? You are trying to break a very useful concept of RAII.

网友答案:

I don't think you can prevent the destructor from being called, and I'm not sure why you would want to. The object must be destroyed before the memory is freed - if the superclass allocated some resources, its destructor must free them before the object's memory is free'd.

Edit after your edit: Yes, the destructors clean up anything they allocated but don't deallocate the object's memory. The delete method you're writing does that.

BTW, nice name. :-)

网友答案:

If you are concerned about (a) grabbing memory from a specific pool and (b) controlling when destructors are called one option is placement new:

void* raw = allocate(sizeof(Foo));  // line 1
Foo* p = new(raw) Foo();            // line 2

p->~Foo();   // explicitely call destructor

(code taken from above link to C++ FAQ)

网友答案:

Answering your question, yes constructors and destructors are called whether you overload new/delete or not.

Answering a question that you didn't ask, whether it's a good solution for using the objects with memory pool, the answer is generally -- "no". What you want is your classes, working with memory pool to take an allocator class. It allows a lot more flexibility and typically you don't just have one class, but many that would be put in memory pool, so you don't want to have a mass overload of all new/delete functions. Also, it's not unusual to have several allocation schemes (and therefore allocators), but you can overload new/delete only once.

相关阅读:
Top