Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noexcept operator with lambdas. MSVC bug?

It appears that MSVC treats all lambdas as noexcept. This code compiles in msvc 19.28 (checked in Compiler Explorer), but expectedly fails the static assertion in gcc:

void foo() {
  auto lambda_may_throw = [] {};

  static_assert(noexcept(lambda_may_throw()));
}

What is interesting is that I googled a bit but was unable to find any info on this issue. Is this really an msvc bug or just me failing to understand something?

like image 470
Dmitry Bezer Avatar asked Feb 07 '21 11:02

Dmitry Bezer


People also ask

What is the noexcept exception specification in C++ Lambda expressions?

You can use the noexcept exception specification to indicate that the lambda expression does not throw any exceptions. As with ordinary functions, the Microsoft C++ compiler generates warning C4297 if a lambda expression declares the noexcept exception specification and the lambda body throws an exception, as shown here:

What does the noexcept operator do in C++?

The noexcept operator does not evaluate expression . The result is true if the set of potential exceptions of the expression is empty (until C++17)expression is non-throwing (since C++17), and false otherwise.

What is the use of noexcept in Python?

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.

How do you mark a function as noexcept?

Mark a function as noexcept only if all the functions that it calls, either directly or indirectly, are also noexcept or const. The compiler doesn't necessarily check every code path for exceptions that might bubble up to a noexcept function.


1 Answers

The behavior is only observed with /permissive. When compiling with /permissive-, the assert triggers.

So perhaps it is a compatibility extension to support older Visual Studio code.

(You also may observe that it fails with /std:c++latest and compiles with /std:c++17 without specifying /permissive-. This is not the difference in standards, rather /std:c++latest also implies /permissive- by default)

like image 156
Alex Guteniev Avatar answered Oct 25 '22 17:10

Alex Guteniev