10

Consider this:

#include <iostream>
#include <functional>

std::function<void()> task;
int x = 42;

struct Foo
{
   int& x;

   void bar()
   {
      task = [=]() { std::cout << x << '\n'; };
   }
};

int main()
{
   {
      Foo f{x};
      f.bar();
   }

   task();
}

My instinct was that, as the actual referent still exists when the task is executed, we get a newly-bound reference at the time the lambda is encountered and everything is fine.

However, on my GCC 4.8.5 (CentOS 7), I'm seeing some behaviour (in a more complex program) that suggests this is instead UB because f, and the reference f.x itself, have died. Is that right?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

2 Answers2

11

To capture a member reference you need to utilize the following syntax (introduced in C++14):

struct Foo
{
   int & m_x;

   void bar()
   {
      task = [&l_x = this->m_x]() { std::cout << l_x << '\n'; };
   }
};

this way l_x is an int & stored in closure and referring to the same int value m_x was referring and is not affected by the Foo going out of scope.

In C++11 we can workaround this feature being missing by value-capturing a pointer instead:

struct Foo
{
   int & m_x;

   void bar()
   {
      int * p_x = &m_x;
      task = [=]() { std::cout << *p_x << '\n'; };
   }
};
underscore_d
  • 6,309
  • 3
  • 38
  • 64
user7860670
  • 35,849
  • 4
  • 58
  • 84
  • 2
    Agreed. Only available since C++14 though right? Think I'm going to have to declare a pointer somewhere and take that by value. – Lightness Races in Orbit Dec 01 '17 at 11:54
  • Though my question is about C++11, this is close enough as it confirms the problem and suggests a solution I'd like to use in the future - and converting to a C++11 solution is now trivial (and works, btw). – Lightness Races in Orbit Dec 01 '17 at 12:18
3

You can capture a reference member in C++11 by creating a local copy of the reference and explicit capture to avoid capturing this:

void bar()
{
    decltype(x) rx = x; // Preserve reference-ness of x.
    static_assert(std::is_reference<decltype(rx)>::value, "rx must be a reference.");
    task = [&rx]() { std::cout << rx << ' ' << &rx << '\n'; }; // Only capture rx by reference.
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • And this doesn't suffer from the same problem purely because we've eliminated the `this` intermediary? – Lightness Races in Orbit Dec 01 '17 at 12:39
  • @LightnessRacesinOrbit Yes, because it uses explicit capture `this` is not captured. And if the member is not a reference it breaks at compile time. – Maxim Egorushkin Dec 01 '17 at 12:42
  • I get that `this` doesn't come into your example - I'm trying to arrive at unquestionable proof that this one change results in a wholly valid program – Lightness Races in Orbit Dec 01 '17 at 12:47
  • 1
    @LightnessRacesinOrbit All these references end up referring the global `x`, since initializing a reference with a reference does not make a reference to a reference, if I understand you correctly. – Maxim Egorushkin Dec 01 '17 at 12:52
  • Right, which is what I thought my original solution would do, but it didn't, hence my caution - I guess I was hoping you'd flesh it out a bit with a proof to that end – Lightness Races in Orbit Dec 08 '17 at 17:42