Is memory freed when I throw an exception?

I discussed some colleges about what happens when you throw an exception in a dynamically allocated class. I know that malloc is called, and then the class constructor. The constructor never returns, so what happens with malloc?

Consider the following

class B
{
    public:
        B()
        {
            cout << "B::B()" << endl;
            throw "B::exception";
        }

        ~B()
        {
            cout << "B::~B()" << endl;          
        }
};

void main()
{
    B *o = 0;
    try
    {
        o = new B;
    }

    catch(const char *)
    {
    cout << "ouch!" << endl;
    }
}

What happens to the malloced memory 'o', is it leaking? Does CRT save constructor exception and free memory?

Cheers Rich

+5
source share
4 answers

Call

new B();

allows two things:

  • selection using the new () operator (either global or a specific class, possibly a placement with syntax new (xxx) B())
  • .

, delete. , , , :: operator delete(). delete x; delete[] x; , new.

, B not, ( B B) delete. , , , B.

+9

, , , B .

+6

, o, , . , . :

delete o;

RAII - . . , - . , , .

, . , . , . , . . :

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

+2

++ 2003 Standard 5.3.4/17 - :

- , , , , , . , . [: , ; . ]

, - , ( , new/delete ). , , , .

, , , , - , , .

+1

All Articles