Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 413
Arafat Hasan Avatar asked Dec 24 '22 13:12

Arafat Hasan


1 Answers

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.

like image 148
gsamaras Avatar answered Dec 29 '22 11:12

gsamaras