mardi 1 décembre 2015

Scope of Stack Allocated Class in a Vector [duplicate]

I have classes organized as follows:

#include <iostream>
#include <vector>

struct Tracker
{
    int a = 0;

    void update()
    {
       a++;
    }
};

struct OtherClass
{
    std::vector<Tracker> activeTrack;

    void updateAll()
    {
       for (Tracker tr : activeTrack) {
           tr.update();
       }
    }
};

int main()
{
    OtherClass o;
    o.activeTrack.resize(1);
    o.updateAll();  // does nothing?!

    std::cout << o.activeTrack[0].a << '\n';  // Is 0; should be 1!
}

(live demo)

Is there something very simple that I am not understanding about how stack allocated objects behave in vectors?

Aucun commentaire:

Enregistrer un commentaire