Should I use noexcept for simple functions that obviously cannot throw?

2.1k views Asked by At

Item 14 of "Effective Modern C++" recommends declaring functions noexcept whenever they don't emit exceptions. I have a class with a number of small member functions that cannot throw for very trivial reasons e.g. they only perform simple mathematical operations on PODs. Should I declare such functions noexcept? It seems like overkill to me when even the compiler can surely detect that there is no possibility of throwing.

EDIT: To clarify my question somewhat, the advice given in this question is to "use it when it's obvious that the function will never throw." But if it's obvious (even to the compiler) that the function will never throw, why use noexcept at all? Note that I would have to mark the overwhelming majority of the functions my program as noexcept, which I will only do if given a compelling reason.

1

There are 1 answers

0
Karoly Horvath On BEST ANSWER

But if it's obvious (even to the compiler) that the function will never throw, why use noexcept at all?

That knowledge can be only inferred by knowing the definition of the function. The callers will likely include only the header, which contains the declaration. No information there. Your best chance is that the link time optimizer notices the implicit noexcept property and removes the exception handling (talking purely about theoretical considerations, not sure if compilers actually do this...).

This, of course, it's not possible in several circumstances, for example if you use your object polymorphically. Though your implementation is implicity noexcept, the function of the subclass might very well throw.

As a sidenote, life is usually fine and dandy without noexcept, so unless there's a specific reason you want to use it, e.g. a public API, a performance sensitive tight loop, coding standards, etc. you're free to omit it. Do not micro optimize or waste time.