overloading operator delete, or how to kill a cat?

前端 未结 5 778
时光说笑
时光说笑 2021-01-19 15:15

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

相关标签:
5条回答
  • 2021-01-19 15:38

    You should know that you can't perform delete on a single address more than once.

    0 讨论(0)
  • 2021-01-19 15:42

    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.

    0 讨论(0)
  • 2021-01-19 15:50

    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.

    0 讨论(0)
  • 2021-01-19 15:57

    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.

    0 讨论(0)
  • 2021-01-19 16:04

    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 :))

    0 讨论(0)
提交回复
热议问题