Click here to Skip to main content
15,887,444 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello,

If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.

What I have tried:

If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.
Posted
Updated 19-Jan-17 21:19pm

Just handle the exceptions inside a catch all block and rethrow the exception:
C++
MyClass::MyClass() :
    member1(NULL)
    ,member2(NULL)
{
    // Initialise all pointers to memory to be allocated with NULL here or
    // as shown above.
    // Then delete can be safely called for them.
    //member1 = NULL;
    //member2 = NULL;
    try
    {
        // Memory allocation
        member1 = new Member1Type;
        member2 = new Member2Type;
    }
    catch (...)
    {
        // Cleanup here deleting all allocated memory
        delete member2;
        delete member1;

        // Re-throw the exception so that it can be handled again
        throw();
    }
}

Because freeing the memory is usually also done in the destructor, it is common to write a cleanup function that can be called from the destructor and within the above catch block.
 
Share this answer
 
Comments
CPallini 20-Jan-17 3:17am    
5.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900