Delete calling destructor but not deleting object?

倾然丶 夕夏残阳落幕 提交于 2019-11-29 08:49:41

You're misunderstanding what delete does. All delete does is call the destructor, and tell the allocator that that memory is free. It doesn't change the actual pointer. Anything beyond that is undefined.

In this case, it does nothing to the actual data pointed to. That pointer points to the same data it pointed to before, and calling methods on it works just fine. However, this behavior is not guaranteed; in fact, it's explicitly unspecified. delete could zero out the data; or the allocator could allocate that same memory for something else, or the compiler could just refuse to compile this.

C++ allows you to do many unsafe things, in the interest of performance. This is one of them. If you want to avoid this kind of mistake, it's a good idea to do:

delete ptr;
ptr = NULL;

to ensure that you don't try to reuse the pointer, and will crash immediately if you do rather than having undefined behavior.

Calling ptr->method("2.5") after delete ptr has undefined behaviour. This means anything can happen, including what you're observing.

In this code:

MyClass* ptr = new MyClass;
ptr->method("1");
delete ptr;
ptr->method("2.5");

you are accessing the memory that has already been freed, which yields undefined behavior, which means that anything can happen including the worst case: that it seems to work correctly.

That's one of the reasons why it is a good practice to set such a pointer to NULL rather than allowing this kind of stuff happen:

delete ptr;
ptr = NULL;

although the best thing to do is to completely avoid using pointers if possible.

you are accessing the memory, which is not reset until it is used by another new call or so.. however it is a good practice every time you call delete, is to set the pointer to NULL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!