tahsmith tahsmith - 2 months ago 4
C++ Question

When is a lambda trivial?

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.


#include <type_traits>
#include <iostream>
using namespace std;

int main()
auto lambda = [](){};

cout << boolalpha << is_trivially_copyable<decltype(lambda)>{} << endl;

This produces
on vs140 but
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.


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:

... An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

  • the size and/or alignment of the closure type,
  • whether the closure type is trivially copyable (Clause 9),
  • whether the closure type is a standard-layout class (Clause 9), or
  • whether the closure type is a POD class (Clause 9).


(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.