Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will an exception thrown from a noexcept function parameter's constructor immediately result in a call to std::terminate()?

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");
like image 839
masrtis Avatar asked Mar 25 '16 18:03

masrtis


People also ask

What happens if Noexcept function throws exception?

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.

Can a constructor be Noexcept?

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.

What does Noexcept false do?

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.

What is the use of Noexcept in C++?

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.


1 Answers

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.

like image 90
TerraPass Avatar answered Oct 10 '22 15:10

TerraPass