Destructor not being called when leaving scope

后端 未结 8 528
离开以前
离开以前 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条回答
  •  猫巷女王i
    2021-01-03 12:31

    Use std::unique_ptr or std::shared_ptr instead of raw pointer. It the best way to avoid memory leaks or double free.

    That is the right way in modern C++.

    int myfunc (cl1 *oarg) 
    {
        cout << "myfunc called" << std::endl;
        cl1 obj1(222,"NY");
        std::unique_ptr obj2( new cl1 );
        oarg->disp();
    }
    

提交回复
热议问题