As show by pfultz2 there is a work-around for static initialization of lambda functions. One of the steps mention dereferencing a nullptr of pointer to lambda function type.
template <typename T> typename std::remove_reference <T>::type * addr (T && t)
{
return & t;
}
constexpr auto f = true ? nullptr : addr ([] (int arg) { return arg + 1; });
int main ()
{
assert (((*f) (1) == 2));
}
Going through the spec and another question C/C++ nullptr dereference I have trouble understanding whether *f
is undefined behaviour or not. What sections in the spec would make this not undefined behaviour?
That's the wrong question to ask. There's no program where one part of the standard explicitly says it's undefined, and another part of the standard says it's defined anyway.
The question you link to is about taking the address of a dereferenced null pointer. That's not what you're doing here. What you're doing here is calling a member function through a null pointer.
(*f) (1)
meansf->operator() (1)
. That's explicitly invalid, will fail at run-time with GCC or clang if-fsanitize=undefined
option, and may otherwise cause unpredictable behaviour due to the optimiser assumingf != null
.Quoting from N4140 (roughly C++14), but it's not different in other versions of the standard: