As you know, if an exception is thrown in the class constructor, the object is not considered created and its destructor is not called.

Consider this class:

class A { class B { public: void operator =(char* v) { _v = v; } ~B() { delete[] _v; } private: char* _v; }; B _b; public: A() { _b = new char[10]; throw 1; } ~A() { std::cout << "~A()" << std::endl; } }; int main() { try { A a; } catch(...) { } } 

In this case, there will be no memory leak. But why will a class B destructor be called? Where do we get to it? After all, the object containing it will not be destroyed.

  • one
    This object of class A will be considered not created, and an object of class B , which is a field of the created object of class A , will be created. Accordingly, when throwing an exception from the class A constructor, the code generated by the compiler will be invoked to destroy the already created class A fields. - VTT

3 answers 3

But why will a class B destructor be called? Where do we get to it?

The destructor for the field A::b will be automatically called by the constructor of class A when an exception occurs.

    Right here

     A() { _b = new char[10]; 

    since you have not written an explicit constructor call for b_ , the default constructor will be called.

    One could rewrite this piece as

     A():_b(new char[10]) { 

    of course by writing the appropriate constructor for B

    • I apologize, a typo in the message, not the designer, but the destructor - Rikitikitavi
    • And the destructor will be called because the constructor was called! (About which I wrote - read about the default constructor). - Harry
    • Destructor is called when going out of scope, where does this happen? - Rikitikitavi
    • one
      When an exception is thrown, all objects created by this time in the try block are destroyed. Everything. - Harry

    The class constructor b will be called when the class constructor A is called, because you need to initialize the class variables. And then here _b = new char[10]; operator= will be called.

    • I apologize, a typo in the message, not the designer, but the destructor - Rikitikitavi
    • one
      according to the c ++ standard, throwing an exception in the constructor will unwind the stack, during which the destructors of the class variables (mistakenly called "fields") that threw the exception will be called. - KoVadim