Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my code ill-formed if I intentionally mark a function [that I know may probably throw] noexcept to terminate immediately in case of exception? [duplicate]

Tags:

c++

noexcept

I know, marking a function noexcept may be useful in order to get many awesome optimizations [in some cases], such as move semantics, for example. But assume, I have a function in my code that does very critical stuff, and, if this function fails, that would mean that something so bad happened that it is impossible to recover, and the program should be terminated immediately. What if I intentionally mark such a function noexcept even if I admit the probability of exception, just to kill the program if it happens?

Something tells me this is not what it should be used for, but is it a valid use of noexcept?

like image 321
Alexey104 Avatar asked Dec 29 '25 21:12

Alexey104


1 Answers

This is defined behavior, that's specified in the standard. It is informally described as follows:

Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function std::terminate is called:

There's even a given example, over there, that does exactly that.

Note that a compiler may issue an advisory diagnostic, if it detects this situation, but this is still well-formed code.

like image 95
Sam Varshavchik Avatar answered Jan 01 '26 13:01

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!