Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda cannot access reference

Tags:

c++

c++11

lambda

I have a problem with a lambda function in C++: I'm trying to define an asynchronous loader that fills an array of object given a list of string as input.

The code looks like this (not exactly, but I hope you get the idea):

void loadData() {
    while (we_have_data()) {
        std::string str = getNext();
        array.resize(array.size() + 1);
        element &e = array.back();
        tasks.push_back([&, str] () {
            std::istringstream iss(str);
            iss >> e;
        }
    }

    for (auto task: tasks) {
        task();
    }
}

When at the end I scan the list of tasks and execute them, the application crashes on the first access to the variable e inside the lambda. If I run inside a debugger, I can find the right values inside the object e itself. I am doing something wrong, but I don't really understand what.

like image 650
G B Avatar asked Jul 25 '26 10:07

G B


2 Answers

You are holding a dangling reference. When you do

tasks.push_back([&, str] () {
    std::istringstream iss(str);
    iss >> e;
}

You capture by reference the element returned by array.back() since a reference to e is actually a reference to whatever e refers to. Unfortunately resize is called in the while loop so when array is resized the references to back() are invalidated and you are now referring to an object that no longer exist.

like image 176
NathanOliver Avatar answered Jul 27 '26 22:07

NathanOliver


The scope of element& e is the while-loop.

After every iteration of the while-loop, you have lambda functions with a captured reference to different e's, which have all gone out-of-scope.

like image 28
Lorenz Rusch Avatar answered Jul 28 '26 00:07

Lorenz Rusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!