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

Viewed 2759

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.

3 Answers

It is not possible to perform just from a constructor. If you throw an exception then applications need to set up a proper exception handling code at entry points, because if you just thrown an exception that won't be handled then compiler is allowed to skip stack unwinding and cleanup.

If you don't want to use use exceptions, you can have an init method in class B that returns a return code:

class B {
public:
    B(/*parameters that will be used by init*/) : ...
    int init(); // actually initialize instance and return non 0 upon failure
}
Related