6

With C++ lambdas, what happens when you capture a reference by reference? Are you capturing a reference to a local object on the stack (the reference itself), or a reference to the object being referred to? Eg in the following code:

int& TestClass::returnReference()
{
        static int i=0;
        return i;
}

std::function<void ()> TestClass::testFunction()
{
        int& memberRef = this->someIntMember;
        int& intRef = returnReference();

        auto lambda =
        [&]
        {
                // What happens when you capture a reference by reference
                // like memberRef or intRef?
        };

        return lambda;
}
Nick Kovac
  • 487
  • 3
  • 10
  • 3
    Related [Capturing a reference by reference in a C++11 lambda](http://stackoverflow.com/questions/21443023/capturing-a-reference-by-reference-in-a-c11-lambda)? – sergej Apr 22 '16 at 11:28
  • 1
    I think (actually, hope) the intent of the language is that you get a reference to the object that the reference variable refers to, but @sergej's link makes me wonder... – molbdnilo Apr 22 '16 at 11:35

1 Answers1

7

The standard actually mandated it needed to capture the variable, not what it referred to. This was a bug in the standard, and the only case in C++ where this kind of thing could happen.

There is a defect report and suggested resolution (thanks @t.c.) that changed it to capture the referred-to eintity.

In theory, there is a low-cost reference-capture technique that captures the stack pointer and uses offsets known at the point of lambda declaration (plus maybe this) that would use the fact we need only capture a reference by variable not contents. However no compiler I know of used it, and the defect report implies that references you cannot alias into locals/globals cannot be treated this way.

In short, the standard says the wrong thing, but there is no practical problem as no compiler followed the letter of the standard, but rather did the right thing. And future compilers would have to be in violation of the suggested defect resolution to have the bad behaviour.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524