Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noexcept of a function returning a class having throwing destructor

In the following code, I thought that the assertion shouldn't fire but it does.

struct A
{
  ~A() noexcept(false);
};

A f() noexcept;

int main()
{
  static_assert(noexcept(f()), "f must be noexcept");
}

The function f() is noexcept obviously, but noexcept(f()) is evaluated to false. (in both of gcc and clang)

Am i missing something or is it a bug?

like image 946
Inbae Jeong Avatar asked Mar 21 '16 10:03

Inbae Jeong


People also ask

Are destructors Noexcept?

An implicit declaration of a destructor is considered to be noexcept(true) according to [except. spec], paragraph 14. As such, destructors must not be declared noexcept(false) but may instead rely on the implicit noexcept(true) or declare noexcept explicitly.

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

Should constructors be Noexcept?

In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.

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.


Video Answer


1 Answers

The noexcept operator on an expression e tells you whether the set of potential exceptions of the expression is empty. This set contains the potential exceptions of the destructor, as per [except.spec]/(13.2):

If e implicitly invokes one or more functions (such as an overloaded operator, an allocation function in a new-expression, or a destructor if e is a full-expression (1.9)), S is the union of: [...] the sets of types in the exception specifications of all such functions

like image 87
Kerrek SB Avatar answered Oct 19 '22 15:10

Kerrek SB