Home Dashboard Directory Help
Search

Capturing variables in nested lambdas by DanDan19


Status: 

Closed
 as Won't Fix Help for as Won't Fix


9
0
Sign in
to vote
Type: Bug
ID: 560907
Opened: 5/23/2010 5:49:42 AM
Access Restriction: Public
2
Workaround(s)
view
6
User(s) can reproduce this bug

Description

I am not sure if this is a bug or a side effect of lambda closures but it is unexpected behaviour. Captured variables do not seem to be available for nested lambdas.
Consider the following code:

std::vector<int> c1;
int v = 10; <--- I want to capture this variable

std::for_each(
    c1.begin(),
    c1.end(),
    [v](int num) <--- This is fine...
    {
        std::vector<int> c2;

        std::for_each(
            c2.begin(),
            c2.end(),
            [v](int num) <--- error on this line, how do I recapture v?
            {
                // Do something
            });
    });

I would expect the variable v to be available to the inner lambda.
Details
Sign in to post a comment.
Posted by Wyck on 2/1/2012 at 11:27 AM
Epic fail! :( This is a terrible shortcoming of capture binding. The ability to capture from nested labmda function scope through automatic captures is essential.

I would like this escalated, please! Please provide a fix.
Posted by Matthew Bradbury on 12/13/2011 at 7:16 AM
I've just his this issue with nested this captures. Would it be possible to reconsider?
Posted by Microsoft on 6/16/2010 at 1:44 PM
Hi - this does seem to be a bug in the compiler. You should be able to work around this by putting the captured variable in a local variable in the outer lambda's scope, and capturing that variable in the inner lambda. You can also make the external variable a function static, and then you would not need to capture it at all.

Given the workaround, and the relative severity of this issue, we are not planning to fix this bug in our next release. We will keep this bug in our database and reconsider it for future releases.

Thanks,
Andy Rich
Posted by Microsoft on 5/24/2010 at 7:11 PM
Thanks for your feedback. We were able to reproduce the issue you are seeing. We are routing this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.
Posted by Microsoft on 5/24/2010 at 4:01 AM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
Sign in to post a workaround.
Posted by Wyck on 2/1/2012 at 11:32 AM
Widget w;
foo( [&] () {
bar( [&] () {
    w.Ping();
} );
} );

becomes:

Widget w;
foo( [&] () {
Widget& w_=w; Widget& w=w_; // Bring the name into scope here.
bar( [&] () {
    w.Ping();
} );
} );
Posted by Viorel_ on 5/24/2010 at 12:02 AM
Specify the default capture mode ('='):

std::for_each(
    c2.begin(),
    c2.end(),
    [=](int num) . . .