Sunday, 11 August 2013

Never annotate functions involving dynamic memory allocation as noexcept?

Never annotate functions involving dynamic memory allocation as noexcept?

Assume you have a function that normally can never fail, for example:
std::string convert_integer_to_string(int x);
In pricipal, this would be a candidate for noexcept. However, the
implementation most likely involves involves dynamic memory management, so
it could always throw a std::bad_alloc when allocating memory with the new
operator.
Is it recommended to annotate the function as noexcept?
From a practical point of view, it is extremely difficult to handle
out-of-memory situations in a reasonable way. Most programs just assume
that there is enough memory available. Calling std::terminate, as it would
happen if a noexcept function throws std::bad_alloc, seems to be
reasonable in that case.
For me noexcept is some form of documentation. It is a promise that you
(or the optimizer) can safely assume that this function will never throw.
If you are programming an application that doesn't care about
out-of-memory situations, it is still a valid assumption.
I guess the safest recommendation is to never use noexcept if a
std::bad_alloc exception could be thrown. On the other hand, I wonder if
there are advantages to use noexcept anyway, assuming that you don't care
about out-of-memory situations (i.e., if std::terminate is OK).

No comments:

Post a Comment