Karmen
Karmen

Reputation: 1

Throwing exception from constructor memory leak

In this code, if the if clause is true, an exception is thrown from the CurrentAccount constructor:

void Bank::createAccount(string accountType,int iban,int ownerid,double amount)
{
    Account* toAddAccount=nullptr;
    if(accountType=="CurrentAccount")
    {
        toAddAccount=new CurrentAccount(iban,ownerid,amount);
    }
}

As you can see, the exception is not caught in this method, but is promoted higher on the stack.

I was wondering, will there be memory leak since I don't delete toAddAccount (the CurrentAccount constructor works with ints only)?

Upvotes: 0

Views: 384

Answers (2)

James Poag
James Poag

Reputation: 2380

I think this question has already been answered, but you should be using RAII when building your objects. Specifically (as has been pointed out several times already) is the use of std::unique_ptr (and make_unique depending on your standard).

Account* Bank::createAccount(string accountType,int iban,int ownerid,double amount)
{
    std::unique_ptr<Account> toAddAccount;
    if(accountType=="CurrentAccount")
    {
        toAddAccount=new CurrentAccount(iban,ownerid,amount);
    }

    // presumably more code

    return toAddAccount.release(); // your factories shouldn't care where your accounts are stored.
}

Upvotes: 0

navyblue
navyblue

Reputation: 786

It's not a leak because "new expression" is responsible for cleaning up if during its execution an exception is thrown. In other words, "new expression" allocates memory and then calls CurrentAccount's constructor. If this constructor throws the "new expression" automatically deallocates previously allocated memory.

Upvotes: 3

Related Questions