I'm trying to understand when I should use noexcept
and when I should not.
In my library, I have many methods. Some are using methods from third party, some are using the STL. Some use throw, some don't.
I can put noexcept
statements on all my methods, the compiler just do not complain at all. But I do.
I can check my own throws to know if I should put a noexcept
on a method, but am I supposed to check every signature of the STL methods and third party methods to know if I should put a noexcept
?
I could do that but that seems inefficient, am I missing something here ?
example code where I should NOT use noexcept
if my understanding is correct:
foo::foo() noexcept
{
this->BarPtr = std::make_unique<Bar>();
}
CodePudding user response:
You don't have to chase down anything. If you aren't sure about exceptions being thrown, then your method is "potentially throwing". That's the term used by the standard for operations that are not noexcept
. So don't mark your method if you aren't sure, it's only honest (lack of) advertisement.
That's not to say you should never be bothered about it. For example, move operations that are noexcept
can enable/optimise the use of certain standard containers. So if you are writing a custom one, it's worthwhile to try and determine if you can mark things noexcept
1.
1 - As an anecdote, I dealt once with a class that held a member of a type that was written for C 03. The semantics of the type did permit throwing (it had a narrow contract) for invalid inputs or copies thereof, but we only generated valid ones. So I marked the move operations noexcept
to facilitate use of a standard container that was appropriate.