mercredi 5 mai 2021

Passing vector

I am passing a vector<class *> object by refrence as such

class bar{
private:
    int y;
public:
    void increment();
    void set(int p);
}

void bar::increment(){
    y++;
}

void bar::set(int p){
    y = p;
}


void someFunction(vector<bar*> &arr){
    bar tmp;
    tmp.set(1);
    arr.push_back(tmp);
    tmp.set(2);
    arr.push_back(tmp);
    tmp.set(3);
    arr.push_back(tmp);
    tmp.set(4);
    arr.push_back(tmp);
    cout << "size of vector is " << arr.size()<<endl;
}

int main(){
    vector<bar*> foo;
    auto t1 = thread(someFunction, ref(foo));
    t1.join();
    bar f2;
    f2.set(0);
    foo.push_back(f2);
    cout << "size of vector at end of main is " << foo.size()<<endl;
    return 0;
}

This does compile however the resulting values are both 0 instead of 4 and 5. Can I please get any insight into this. Thanks!

Aucun commentaire:

Enregistrer un commentaire