Search code examples
c++c++11c++14exitexit-code

How to end C++ code directly from a constructor?


I would like my C++ code to stop running with proper object cleanup if a certain condition is met; in a constructor of a class.

class A {
public:
    int somevar;
    void fun() {
        // something
    }
};

class B {
public:
    B() {
        int possibility;
        // some work
        if (possibility == 1) {
            // I want to end the program here
            kill code;
        }
    }
};

int main() {
    A a;
    B b;
    return 0;
}    

How can I terminate my code at that point doing proper cleanup. It's known that, std::exit does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup. So std::exit is not a good idea.


Solution

  • You should throw an exception, when the constructor fails, like this:

    B() {
      if(somethingBadHappened)
      {
        throw myException();
      }
    }
    

    Be sure to catch exceptions in main() and all thread entry functions.

    Read more in Throwing exceptions from constructors. Read about Stack unwinding in How can I handle a destructor that fails.