I am fairly certain I know the answer to this question, but I seem to have 2 different compilers giving me different results. Given the following code:
1 2 3 4
void test(const Foo& bar)
{
function<void()> func = [bar](){ /* Do something with bar */ };
}
"bar" should be being captured by value, but since bar is a reference, it only captures the reference as the value, and not the value actually referenced to by bar. So if the original object passed by reference into test() goes out of scope, then it will create a dangling reference. Correct?
since bar is a reference, it only captures the reference as the value
References are not objects, they have no values that could be copied. They are only named aliases. Capture by value makes a copy of the object named by bar.
(okay, there is one exception having to do with capturing references to a functions by value)
I had original thought that the value referenced by bar would be copied, and as far as I understood it that is the defined behavior. However I appear to be running into a compiler optimization that says otherwise, which is why I started to think otherwise (hence the original example).
When passing lambda functions to different threads and I have passed the bar in as "const Foo&" vs "Foo" there are times that my values are wrong or gone, depending on when the original value has left scope.
So just to be clear. When capturing a value that is defined as a const reference into a lambda (like the original example) the defined behavior is that the referenced object is copied by value, thus scope changes in the original value should have no impact on the future execution of the lambda.