Given the following class declaration:
class phone_number
{
public:
explicit phone_number( std::string number ) noexcept( std::is_nothrow_move_constructible< std::string >::value );
}
phone_number::phone_number( std::string number ) noexcept( std::is_nothrow_move_constructible< std::string >::value )
: m_originalNumber{ std::move( number ) }
{
}
Will the following line of code end up calling std::terminate()
immediately due to the noexcept specification if an exception is thrown from the string constructor?
const phone_number phone("(123) 456-7890");
If any functions called between the one that throws an exception and the one that handles the exception are specified as noexcept , noexcept(true) (or throw() in /std:c++17 mode), the program is terminated when the noexcept function propagates the exception.
Using noexcept in the big four (constructors, assignment, not destructors as they're already noexcept ) will likely cause the best improvements as noexcept checks are 'common' in template code such as in std containers.
In contrast, noexcept(false) means that the function may throw an exception. The noexcept specification is part of the function type but can not be used for function overloading. There are two good reasons for the use of noexcept: First, an exception specifier documents the behaviour of the function.
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.
Since all the parameters are evaluated before the function is invoked, an exception, emitted by a parameter's constructor, would not violate noexcept
contract of the function itself.
To confirm this, here's what I've tried, approximating your example:
class A
{
public:
A(const char *)
{
throw std::exception();
}
};
void f(A a) noexcept
{
}
int main()
{
try
{
f("hello");
}
catch(std::exception&)
{
cerr<< "Fizz..." << endl;
}
return 0;
}
The output, unsurprisingly, was Fizz...
and the program exited normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With