4

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.

Arafat Hasan
  • 2,811
  • 3
  • 21
  • 38

3 Answers3

8

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
3

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.

user7860670
  • 35,849
  • 4
  • 58
  • 84
-1

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
}
ytoledano
  • 3,003
  • 2
  • 24
  • 39
  • 2
    The purpose of a constructor is the very *"init"* method you are talking about, only that a constructor is far less evil. Example, how is he supposed to *"init"* *member-data* such as `std::vector`? And how should he write `B`'s destructor? – WhiZTiM Oct 01 '17 at 18:37
  • I know this, but sadly, there are no good ways to go about this in C++ without exceptions. Also see first linked question, an init method is the way to do this if you don't want to throw an exception. – ytoledano Oct 01 '17 at 18:47
  • What makes you think that OP doesn't want to use exceptions? And question is actually about terminating program executing proper cleanup, not about construction failure handling in general. With error codes developer will need to set up chain of return code checks up to entry point. – user7860670 Oct 01 '17 at 18:49
  • A lot of developers don't want to throw exceptions or aren't allowed to, there are many reasons for this. I'm not saying OP shouldn't throw an exception, I'm saying that if that were the case, this answer is the alternative to the proposed solution. – ytoledano Oct 01 '17 at 18:52