Boost logo

Boost :

Subject: Re: [boost] [C++11] If you have an old class with a throwing destructor...
From: Niall Douglas (s_sourceforge_at_[hidden])
Date: 2013-09-09 17:57:05


On 9 Sep 2013 at 13:11, Nevin Liber wrote:

> > In C++03 it was always best practice to *always* wrap your
> > destructors in a try...catch clause.
>
> No; the best practice is not to throw from a destructor.

Sorry, my unclear phrasing again ... by wrapping destructors I
specifically meant:

destructor::~destructor()
{ try {
   ...
} catch(...) { /* do something useful */ } }

Indeed I once had some python executed by my build script to
auto-insert those destructor wrappers because I kept forgetting to do
it.

The problem is that unless some code is specifically marked as
noexcept, you have to assume it can throw, and as destructors ought
to be noexcept, that means lots of try...catch verbiage.

> > As an aside, we could really do with some new compiler warnings on
> > this actually.
>
> I'm not sure what the warning would be, as move constructors are allowed to
> throw.

They are, but equally if you think it through an exception throwing
move constructor is about as useful as an exception throwing
destructor (i.e. somewhat so, but it is wise to choose a different
route where possible). I'm willing to bet US$1 that C++ 2x will make
move constructors noexcept if everything they call is noexcept ... :)

Anyway, it's more a question of good style. GCC has a class of
warnings for style, and clang's static analyser is another case
example. Those would be ideal for this kind of warning.

> > I already get caught enough times forgetting to mark
> > move constructors as noexcept, without which some STL implementations
> > will silently disable move construction completely.
>
> That seems buggy, other than the well-defined cases such as vector using
> the equivalent of move_if_noexcept under the covers when growing a vector.

I think it's buggy if they silently disable move construction and
don't tell you (older versions of libstdc++ I'm looking at you).
libc++ at least is kind enough to refuse to compile, perhaps even a
bit too anally so.

Ideally a STL should issue a compiler warning if it refuses to use
you move constructor for some reason. It is, after all, a quality of
implementation issue.

Niall

-- 
Currently unemployed and looking for work.
Work Portfolio: http://careers.stackoverflow.com/nialldouglas/



Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk