Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noexcept specifier with default arguments construction

Tags:

Take the following example code:

void test(const Item& item = Item()) {
   ...
}

Assume that, once item has been passed to the function, this cannot throw.

The question is: the function should be marked noexcept or noexcept(noexcept(Item()))?

IHMO, the former should be ok, but I am not sure. A quotation from the standard would be very appreciated!

like image 785
dodomorandi Avatar asked May 10 '18 12:05

dodomorandi


People also ask

What is Noexcept specifier 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.

When should you use Noexcept?

E. 12: Use noexcept when exiting a function because of a throw is impossible or unacceptable. you don't care in case of an exception. You are willing to crash the program because you can not handle an exception such as std::bad_alloc due to memory exhaustion.

Is Noexcept required?

Explicit instantiations may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations.

Is Noexcept faster?

Theoretically speaking, noexcept would improve performance. But it might also cause some problems on the other hand. In most of cases, it shouldn't be specified because the pros are too few to be considered and it might make your code upgrading painful.


1 Answers

Default arguments are shortcut notations for the caller of function. So, when the function executes, the construction is already complete.

Thus, noexcept should be sufficient.

In the standard [dcl.fct.default] states:

If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a default argument. Default arguments will be used in calls where trailing arguments are missing.

Example: the declaration void point(int = 3, int = 4); declares a function that can be called with zero, one, or two arguments of type int. It can be called in any of these ways: point(1,2); point(1); point(); The last two calls are equivalent to point(1,4) and point(3,4) , respectively.

Also there is a note (in [intro.execution] Program execution):

Subexpressions involved in evaluating default arguments (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

like image 144
Philipp Claßen Avatar answered Nov 15 '22 13:11

Philipp Claßen