Is dereferencing nullptr to lambda function undefined behaviour?

305 views Asked by At

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?

1

There are 1 answers

1
AudioBubble On BEST ANSWER

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) means f->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 assuming f != null.

Quoting from N4140 (roughly C++14), but it's not different in other versions of the standard:

9.3.1 Nonstatic member functions [class.mfct.non-static]

2 If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.