3

Consider the following piece of code for C++:

class A {
  A() {
    if(some condition)
      exit(1);
  }
};

Is this legitimate to do? i.e. exiting directly from a constructor before it has completed. Are there any side effects to this?

  • Yes it is legitimate, but do you really want to shut down the entire application just like that? [See this](https://stackoverflow.com/questions/22843189/exit-call-inside-a-function-which-should-return-a-reference/22843464#22843464) – PaulMcKenzie Oct 09 '20 at 14:59

3 Answers3

2

Yes, this is legal C++. However, be aware that this doesn't unwind the stack like a call to throw; would do, so the destructors of any stack-allocated variables will not be called. But it will call the destructor of static variables. See the documentation of std::exit() for more information.

G. Sliepen
  • 7,637
  • 1
  • 15
  • 31
1

Is this legitimate to do?

Technically yes. That said, I cannot think of a reasonable use case.

Are there any side effects to this?

exit has effect of terminating the process (static objects are destroyed; automatic objects are not). Calling it within a constructor doesn't change that.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

There are different points of view:

  • Is it correct code from a compiler point of view?

    Yes. The exit function can be called at any point from a C++ program and will cause the program to exit as soon as possible.

  • Are there possible unexpected side effects?

    Yes. The destructors of any members or base classes of the object under construction will not be called. For example if some of them were responsible for writing data on disk that should be used on next start, that data might not be written.

  • Is there any case where it is legitimate code?

    No. If you need to abort inside an object constructor, you should throw an exception. If the exception is not caught, it will indeed abort the program, but in a clean way, ensuring that any constructed objects (even members of the object in construction) will have its destructor called. And any caller will have an opportunity to do some clean up.

Long story made short: NEVER DO THAT!

cigien
  • 57,834
  • 11
  • 73
  • 112
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • `throw` [does not guarantee object destruction](http://www.eel.is/c++draft/except#handle-9): *If no matching handler is found, the function `std​::​terminate` is called; whether or not the stack is unwound before this call to `std​::​terminate` is implementation-defined* – j6t Oct 09 '20 at 16:49