[&]
means implicit capture by reference.
If you capture something by reference, it only remains in a defined state so long as it exists. You appear to be returning a lambda converted to a std::function
. Capturing by reference is a very bad idea.
The local variable goes out of scope. The reference to it captured in the lambda is now in an undefined state, all use of it is undefined behavior. You then return a copy of this lambda in a std::function
, invoke it, and nasal demons shoot out your nose; or in your case, the pointer doesn't appear null.
Never implicitly capture by reference in a lambda whose lifetime, or whose copies lifetime, will exceed the current scope.
In general, never implicitly capture things in that situation, even with [=]
. Be explicit.
std::function<void(json)> doTheThing() {
void* pointer = nullptr;
return [pointer](json object) {
if(pointer != nullptr) {
std::cout<<"pointer not null";
}
};
}