Sobes.tech
Junior — Middle

What happens to the destructor call if an exception occurs in its constructor?

sobes.tech AI

Answer from AI

If an exception occurs in the constructor of an object in C++, the destructor of that object is not called because the object is considered not fully constructed.

However, destructors of already fully constructed members of the object and base classes, which were successfully constructed before the exception occurred, will be called to properly release resources.

Example:

class A {
public:
    A() { throw std::runtime_error("Error in constructor"); }
    ~A() { std::cout << "Destructor A" << std::endl; }
};

class B {
    A a;
public:
    B() { }
    ~B() { std::cout << "Destructor B" << std::endl; }
};

int main() {
    try {
        B b; // exception will be thrown during creation of a in B()
    } catch (...) {
        std::cout << "Exception caught" << std::endl;
    }
}

In this example, the destructor of B will not be called because the object B was not fully created, but the destructor of A will be called if A was successfully constructed before the exception.