I am a little bit confused with destructors and noexcept
. My understanding was that in C++11 any destructor, including user-defined, is implicitly noexcept(true)
, even if we throw
from it. And one has to specify explicitly noexcept(false)
if they want it to be that way for some reason.
I'm seeing quite the opposite - with GCC 4.7.2, the user-defined destructor, no matter how primitive the class and destructor are, is implicitly noexcept(false)
. What am I missing here? Is there some hidden gotcha with user-defined destructors?
A declaration of a destructor that does not have an exception-specification is implicitly considered to have the same exception-specification as an implicit declaration. An implicit declaration of a destructor is considered to be noexcept(true) according to [except. spec], paragraph 14.
Item 14, page 94: 'By default, all memory deallocation functions and all destructors -both user-defined and compiler-generated- are implicitly noexcept. There is thus no need to declare them noexcept. (Doing so doesn't hurt anything, it's just unconventional.)'
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.
noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something.
This is a known bug (credits to the OP for finding the bug report), and it seems it has been fixed in GCC 4.8.0. For instance, the static assertion below will fire on GCC 4.7.2, but not on GCC 4.8.0:
struct X { ~X() { }; }; int main() { X x; // This will not fire even in GCC 4.7.2 if the destructor is // explicitly marked as noexcept(true) static_assert(noexcept(x.~X()), "Ouch!"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With