Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is memory allocated for an object automatically deleted if an exception is thrown in a constructor?

Tags:

c++

Suppose there is this code:

class CFoo
{
public:
    CFoo()
    {
        iBar = new CBar();
    }
private:
    CBar* iBar;
};

....
CFoo* foo = new CFoo();

When the above line is executed, first memory will be allocated to hold the CFoo object. But then if the line new CBar() throws an exception (due to lack of memory) does the system automatically deallocate the memory that was previously allocated to the CFoo object? I presume it must, but cannot find any explicit reference saying so. If it doesn't how can the memory be deallocated by the coder as it will not have been assigned to foo?

like image 277
David Preston Avatar asked Dec 29 '22 02:12

David Preston


1 Answers

Yes, the memory allocated for the CFoo object will be freed in this case.

Because the exception due to the failed allocation causes the CFoo constructor to fail to complete successfully the new-expression is guaranteed to free the memory allocated for that CFoo object.

This guarantee is specified in 5.3.4 [expr.new] / 17 of ISO/IEC 14882:2003.

Note, that it is always advisable to assign the result of a dynamic allocation to a smart pointer to ensure proper clean up. For example, if there was further code in CFoo constructor and that threw an exception the CBar object already successfully allocated earlier in the constructor would be leaked.

like image 81
CB Bailey Avatar answered Feb 01 '23 17:02

CB Bailey