I am experimenting with overloading operator delete, so that I can return a plain pointer to those who don\'t wish to work with smart pointers, and yet be able to control wh
You should know that you can't perform delete on a single address more than once.
Once the destructor for an object has been called, anything you do with the object is undefined. What you are trying to do is not possible.
You've misused just every C++ concept possible and this causes errors. When delete p;
is called for the first time C++ calls the Cat::~Cat()
destructor which implicitly destroys the std::string
inside the entity. When delete p;
is called the second time Cat::~Cat()
is rerun and it reruns the destructor of the std::string
and this causes undefined behavour crashing the program because I suppose std::string::~string()
doesn't nullify the pointer to the buffer and so when std::string::~string()
tries to release the buffer for the second time with the same address this leads to famous double-free.
The destructor isn't responsible for freeing the memory and u've not prevented this from happening.
The first call is freeing the memory, the second call goes bang.
operator delete
calls the object destructor and after that you are in no man's land. As others pointed out, what you are trying to do is not possible.
What you are doing is also a bit dodgy in the way of inconsistent behaviour when the object is constructed on the heap and on the stack.
With your idea to override operator delete
the object will stay alive depending on some internal logic (the number of lives has reached 9) if constructed using new.
When constructed on the stack (Cat cat("Chesire cat");
) the object will always get destructed when it goes out of scope. In order to achive what you are trying to do you will also need to change the bahaviour of the destructor to "stop destructing". This is not possible, also for very good reasons.
So, if you want ref counting, just implement your own mechanism. After all, you can't call yourself a C++ programmer if you haven't done your own ref count memory management at least once :))