When is a lambda a guaranteed to be trivial, if ever?
I assumed that if it captures only trivial types or nothing, it would be trivial. I don't have any standard-ese to back that up though.
My motivation was in moving some code from Visual C++ 12 to 14 and discovered some static asserts failed when dealing with lambdas I assumed to be trivial.
Example:
#include <type_traits>
#include <iostream>
using namespace std;
int main()
{
auto lambda = [](){};
cout << boolalpha << is_trivially_copyable<decltype(lambda)>{} << endl;
}
This produces false
on vs140 but true
in vs120 and clang. I could not test gcc due to not having gcc >= 5 around. I expect this is a regression in vs140, but I'm not certain of the correct behavior here.
According to the draft standard N4527 5.1.2/3 Lambda expressions [expr.prim.lambda] (emphasis mine):
Thus, it's implementation dependent.
The standard does not specify whether a closure type (the type of a lambda expression) is trivial or not. It explicitly leaves this up to implementation, which makes it non-portable. I am afraid you cannot rely on your
static_assert
producing anything consistent.Quoting C++14 (N4140) 5.1.2/3:
(Emphasis mine)
After parsing the double negation in that sentence, we can see that the implementation is allowed to decide whether the closure type is trivially copyable, standard layout, or POD.
Note that the same wording is also present in C++17 (N4659), [expr.prim.lambda.closure] 8.1.5.1/2.