Destructor not being called when leaving scope

后端 未结 8 474
离开以前
离开以前 2021-01-03 11:50

I am learning memory management in C++ and I don\'t get the why only some of the destructors are called when leaving scope. In the code below, only obj1 destructor is called

相关标签:
8条回答
  • 2021-01-03 12:39

    obj1 is an object of type cl1, with automatic storage duration (It is allocated on the stack, and its lifetime is determined by the scope it is in)

    obj1 is an object of type cl1*. That is, it is a pointer. The pointer also has automatic storage duration, but the object it points to does not. It points to a dynamically-allocated object in the free-store.

    When you leave the scope, then the objects with automatic storage duration get destroyed. obj1 gets destroyed, calling your destructor. And obj2 also gets destroyed, but obj2 isn't of type cl1, so it doesn't call cl1's destructor. It is a pointer, and it does nothing special when it is destroyed.

    Pointers don't own the objects they point to, and so they do nothing to ensure the pointed-to object gets destroyed or cleaned up. (If you want an "owning" pointer, that's what smart pointer classes are for)

    Consider that you can easily have multiple pointers pointing to the same object.

    If a pointer automatically deleted the object it pointed to, then that would lead to errors. An object pointed to by two different pointers would get deleted twice.

    0 讨论(0)
  • 2021-01-03 12:50

    You should use delete for dynamically allocated objects:

    delete obj2;
    

    this calls the destructor and frees memory. You'll be much better off using smart pointers for managing such objects - they will call delete for you even in case of exception being thrown between new and delete.

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