0

Up to C++03 destructors were generally allowed to throw arbitrary exceptions.

In C++11, however, all destructors without an explicit exception specification became noexcept by default. This can be overridden with noexcept(false) but this code won't be accepted by pre-C++11 compilers.

One solution is to detect the need for noexcept(false) by checking compiler-specific #defines, but this still limits applicability of such code to the set of known compilers.

Is there any portable way to allow throwing arbitrary exceptions from destructors in both С++11 and C++03?

  • 1
    The portable way is to **not** throw exceptions from the destructor, be it C++03 or C++11. [Read this](http://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor) for a discussion of why destructors that can throw are a bad idea. And a [GotW article](http://www.gotw.ca/gotw/047.htm) that also talks about it. – Praetorian Jul 04 '14 at 05:27

2 Answers2

1

You can do it using the __cplusplus macro provided by the standard:

#if __cplusplus >= 201103L                // We are using C++11 or a later version
#define NOEXCEPT_FALSE noexcept(false)
#else
#define NOEXCEPT_FALSE
#endif

The far better idea, however, is to simply never throw from a destructor.

T.C.
  • 133,968
  • 17
  • 288
  • 421
0

You don't need to rely on "compiler-specific #defines"...

16.8/1 The following macro names shall be defined by the implementation:

__cplusplus

The name __cplusplus is defined to the value 201103L when compiling a C++ translation unit.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252