Destructor not being called when leaving scope

后端 未结 8 475
离开以前
离开以前 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:30

    If you allocate a object using new

    obj2= new cl1;
    

    Then unless you call delete on it, its destructor won't be called implicitly.

    EDIT: As @David, meantions in comments, One may call destructor of an object explicitly but in my experience there is rarely a need to manually call the destructor unless one is using placement new version of new.

    Variables on stack are implicitly cleaned up(by calling their destructors) when their scope ends.

    Dynamically allocated objects are not implicitly cleaned, it is the responsibility of the user to clean them up explicitly calling delete.

    This is the very reason one should not use raw pointers but use smart pointers.

提交回复
热议问题