Deleting an object in C++

前端 未结 6 1873
清酒与你
清酒与你 2021-02-01 03:56

Here is a sample code that I have:

void test()
{
   Object1 *obj = new Object1();
   .
   .
   .
   delete obj;
}

I run it in Visual Studio, an

6条回答
  •  一向
    一向 (楼主)
    2021-02-01 04:20

    Just an update of James' answer.

    Isn't this the normal way to free the memory associated with an object?

    Yes. It is the normal way to free memory. But new/delete operator always leads to memory leak problem.

    Since c++17 already removed auto_ptr auto_ptr. I suggest shared_ptr or unique_ptr to handle the memory problems.

    void test()
    {
        std::shared_ptr obj1(new Object1);
    
    } // The object is automatically deleted when the scope ends or reference counting reduces to 0.
    
    • The reason for removing auto_ptr is that auto_ptr is not stable in case of coping semantics
    • If you are sure about no coping happening during the scope, a unique_ptr is suggested.
    • If there is a circular reference between the pointers, I suggest having a look at weak_ptr.

提交回复
热议问题