vendredi 24 février 2017

Why is my lambda capturing a pointer by value?

I have the following lambda

    direction->addClickEventListener([=](Ref* sender){

        std::unordered_map<int,int> data;
        rep->getData(DIRECTION, data);
        int last = data[1];
        int rotation = (last + 45)%360;

        LOG("l:%i r:%i",last,rotation);//Always logs l:0 r:45
        direction->setRotation(rotation);
        data[1] = rotation;
        rep->setData(DIRECTION, data);
    });

where getData is:

void getData(DATA_KEY key,std::unordered_map<int,int>& data){
//Modifies data with the appropriate values for key, for the current state of rep
}

void setData(DATA_KEY key,std::unordered_map<int,int>& data){
//Makes a copy of data stores it internally with key
}

rep is pointer, so I thought that whenever the lambda is called, the current value of data will always reflect the current state of rep. But it seems that it is always the value of whatever rep was at the time direction->addClickEventListener was called.

If I want to use the current state of rep, how ghouls I modify my lambda ? Since rep is a pointer, I can't pass it by reference.

Aucun commentaire:

Enregistrer un commentaire