Is it possible to prevent the destructor from running when delete is called in C ++?

In particular, in a library, I have a memory pool that overrides the behavior of new ones and removes certain classes. I want the library users to be able to call delete on instances of these classes, but I need to keep the instances until some specific cleanup action is taken. Is this possible while allowing users to use the usual new / delete? How can you override the default behavior of calling the destructor?

+3


source to share


3 answers


The short answer is no. A call delete

always causes a call to the destructor, and after that the call operator delete

, just like a call new

, first calls the corresponding operator new

one and then runs the object's constructor. If you want to prevent your users from destroying objects you have to prevent them in some way: a) call delete on raw pointers and b) build them on the stack.

If you want to keep the instances alive, it sounds like you want to control your life, so the natural way would be to create objects within your library as well. In addition, it is currently delete

considered bad style to make regular calls in your code as there are smart pointers available that automatically make these calls.



So what you can do is add creator functions to your library that return some kind of smart pointers. It can be either shared_ptr

, or unique_ptr

with a custom deleter that doesn't actually delete the object, but rather passes it back to your library, which will be cleaned up later.

+4


source


Use smart pointers instead of new

/ delete

(which is good practice).

Use a custom deleted item that moves the ownership of the object to the Pending Cleanup list of objects.

For examples of smart pointers, see std::unique_ptr

and std::shared_ptr

.



Another option (which works more and more difficult to get the right) is to store objects only in containers that use custom allocators and spreader functions destroy

and deallocate

carry out "the transition to the staging area for cleaning instead of the actual destruction of its" parts. I would recommend a smart pointer with a custom approach rather than an allocator.

Both of these options (custom removers and custom allocators) allow you to control the exact behavior when an object is "destroyed" by separating the actual end of the object's life from the moment users dispose of it, which is not possible with a statement delete

.

+4


source


delete

runs destructors. This is the basic fact that everyone relies on. If you can somehow disable calling the destructor that you cannot, you will break all expectations. If you don't want your users to call destructors, don't make the destructors available to them. The protected destructor will make it delete

invulnerable.

+2


source







All Articles