Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping destructor being called

Tags:

c++

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.

like image 233
Graeme Avatar asked Jan 25 '11 18:01

Graeme


People also ask

How do you stop a destructor from being called?

The best way to not call a particular destructor is to not create an instance of that object to begin with. Failing that, take the code you don't want to run out of the destructor. I can't conceive any reason why doing this would be legitimate. And, you mentioned the only way.

Why is my destructor being called?

A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde).

When destructors are called when a program ends?

Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends. A program ends and global or static objects exist.

Are destructors automatically called?

What is a destructor? Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.


1 Answers

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.

like image 182
Nikolai Fetissov Avatar answered Sep 23 '22 08:09

Nikolai Fetissov