Reputation: 617
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;
}
Upvotes: 6
Views: 673
Reputation: 275976
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.
Upvotes: 7