Deleting an object in C++

Nima picture Nima · Aug 7, 2010 · Viewed 162.4k times · Source

Here is a sample code that I have:

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

I run it in Visual Studio, and it crashes at the line with 'delete obj;'. Isn't this the normal way to free the memory associated with an object? I realized that it automatically invokes the destructor... is this normal?


Here is a code snippet:

    if(node->isleaf())
    {
        vector<string> vec = node->L;
        vec.push_back(node->code);
        sort(vec.begin(), vec.end());

        Mesh* msh = loadLeaves(vec, node->code);

        Simplification smp(msh);

        smp.simplifyErrorBased(errorThreshold);

        int meshFaceCount = msh->faces.size();

        saveLeaves(vec, msh);

        delete msh;
    }

loadleaves() is a function that reads a mesh from disk and creates a Mesh object and returns it.(think of vec and node->code are just information about the file to be opened)

Should I remove the delete msh; line?

Answer

James McNellis picture James McNellis · Aug 7, 2010

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<Object1> 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.