Deleting an object in C++

前端 未结 6 1872
清酒与你
清酒与你 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:16

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

    This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

    It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

    As an example of automatic resource management:

    void test()
    {
        std::auto_ptr obj1(new Object1);
    
    } // The object is automatically deleted when the scope ends.
    

    Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

    As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

提交回复
热议问题