1

I try to pass a null pointer as reference to a lambda function, but it will receive a memory address instead of staying null.

  function<void(json)> doTheThing(){
  ...
  pointer = nullptr;
  return [&](json object) {
    if(pointer != nullptr) {
       cout<<"pointer not null";
}
}

Any idea how to pass that pointer so it will remain null ?

user3605225
  • 285
  • 1
  • 3
  • 7

1 Answers1

2

[&] 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";
    }
  };
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Please do not upvote my answer above; this is a duplicate. This answer merely exists to explain it to the OP for the OP's particular case. Instead follow the duplicate and upvote there :) – Yakk - Adam Nevraumont Feb 17 '17 at 14:09