About this function
int test(int a,int b)
{
return a/b;
}
If I call test(2,1)
, nothing happens.
But if I call test(2,0)
, it causes undefined behavior.
As a result, should I define it as noexcept
?
BTW, why is std::vector::operator[]
not noexcept
?
Should I define it as
noexcept
?
You certainly can, if you want. It is true in that the function won't throw an exception. It still can fail from division by zero, however.
It depends on what you think noexcept
should mean. The standard library seems to treat it as a keyword meaning the function can't possibly fail, not just that it doesn't throw. If you follow their convention, you shouldn't make it noexcept
. However, if you want noexcept
to mean only that it doesn't throw, then you should.
Either way, you should always use the same convention. Outside of constructors and assignment operators, there isn't a large benefit either way.