jeudi 24 septembre 2015

Data not stored in vector using lambda as it should

I have created a custom data structure which loads data from the disk, then the data structure class calls a callback function for every loaded object. This is all working fine - I just want to give you some background information.

The actual problem is in the following function:

void getData(std::vector<long long> &c) const
{
    c.reserve(myDataStructure.size());
    std::size_t index = 0;

    myDataStructure.forEach([&c, &index] (const long long &data)    //load data
    {
        c[index++] = data;     //line 8
        return true;           //line 9
    });
}

The function is pretty simple: it loads all the data from my custom structure and saves it in a vector. To get better performance I reserve the memory at the beginning. Now, when I run the program in gdb it reaches line 8 multiple times but everytime I check the content of c it is empty. Do I use the lambda function in a wrong way? Btw: I'm using g++ with optimization enabled

Additional info: The following code is working as expected and I don't really see a difference:

void getData(std::function<bool(const MyData&)> f) const
{
    myDataStructure.forEach([&f] (const long long &data)
    {
        MyData d(data);
        //process data
        return f(d);
    });
}

Aucun commentaire:

Enregistrer un commentaire