C++: why it doesn't call a destructor?

后端 未结 3 1213
傲寒
傲寒 2020-12-21 07:32

I use extra brackets in my code. I thought when the destructor should be called after the local variable scope is ended but it doesn\'t work like this:

class         


        
3条回答
  •  悲&欢浪女
    2020-12-21 08:19

    Because you have a pointer to a dynamically allocated object. Only the pointer goes out of scope, not the object it points to. You have to call delete on the pointer in order for the pointee's destructor to get called.

    Try with an automatic storage object instead:

    {
      TestClass test;
    }
    

    Here, the destructor will be called on exiting the scope.

    The use of raw pointers to dynamically allocated objects in C++ is discouraged because it can easily lead to resource leaks like the one shown in your code example. If pointers to dynamically allocated objects are really needed, it is wise to handle them with a smart pointer, rather than to attempt to manually deal with their destruction.

提交回复
热议问题