Exceptions to the static variable constructor / destructor

Hi, I found this line in a web UI tutorial.

What happens when you declare a static object, and destructors throw and exclude?
As with static constructor exceptions, the application will crash.

I can’t understand what the difference is if the object is static or not ...

thanks

+4
source share
1 answer

I'm not sure what you are asking about constructors or destructors that throw exceptions - the problem statement relates to destructors, but the sample code and some comments relate to constructors.

As for the constructors that throw, it depends on whether the static object is local or global. Local static objects are built for the first time when the control passes through the area in which they are defined, and exception handlers should behave normally for them. Global static objects are created before the program enters main() ; since you cannot have a try-catch block in global scope if you create a constructor for a global static object, this basically means that your application crashes before it leaves the initial shutter.

As for destructors, generally speaking, destructors that can throw exceptions pose serious problems. Herb Sutter talks about the reasons why in his book Exceptional C ++, which is available here on Google Books. In principle, if a destructor can throw exceptions, it makes it almost impossible to create code that excludes code. Consider the following example.

 class T { T() {} ~T() { throw 5; } }; void foo() { T t; throw 10; } 

When foo() reaches throw 10; , the control exits the context of foo() , destroying the local object t in the process. This causes a destructor for t , which attempts to throw another exception. In C ++, it is not possible to throw two exceptions at the same time; if the second exception is thrown, the program calls the built-in terminate() function, which does what it resembles, and terminates the program (you can use your own function instead using set_terminate , but this is mainly for performing selective cleaning - you cannot change the fact that the program ends after the function is executed).

To avoid this, make sure that destructors never throw exceptions. This may not matter with static objects because, as celtschk noted, the destructor will not be called until the program terminates anyway, but as a rule, if you find that you are writing a class with a destructor that can generate an exception, you should carefully consider whether this is really the best approach.

+2
source

Source: https://habr.com/ru/post/1485249/


All Articles