Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructors and noexcept

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?

like image 901
lapk Avatar asked Mar 30 '13 17:03

lapk


People also ask

Are destructors Noexcept?

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.

Should I mark destructor Noexcept?

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.)'

What does Noexcept mean?

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.

What is the point of Noexcept?

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.


1 Answers

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!"); } 
like image 128
Andy Prowl Avatar answered Sep 19 '22 06:09

Andy Prowl