class State{
double x,y,z;
std::vector<double *> state = {&x,&y,&z};
void set(int id, double val){*state[id] = val;}
};
Most of the time the set function works fine, as it should. But sometimes it only updates the "state" vector, and not the variable itself, which is super strange since it's just a pointer. So say
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main(){
State s;
s.set(0,0); // works fine
fun1(&s);
}
void fun1(State * s){
s->set(1,10); // this sets y, ok
fun2(s);
}
void fun2(State * s){
s->set(2,20); // this only sets the state[2] and not the z
}
So yeah, super strange. I had a similar code before, but then it was more like
1 2 3 4 5 6 7
class State{
double state[3];
double * x = &state[0];
double * y = &state[1];
double * z = &state[2];
void set(int id, double val){state[id] = val;}
};
and that worked fine. What's going on?
Edit:
I've also tried now
1 2 3 4 5
class State{
double x,y,z;
double * state[3] = {&x,&y,&z};
void set(int id, int val){*state[id] = val;}
}
And this doesn't work either.
Edit2:
Ok, I figured it out. Actually my State class also had an assignment operator like
1 2 3 4 5 6 7 8 9 10 11 12 13
State{
double x,y,z;
double * state[3] = {&x,&y,&z};
void set(int id, double val){ *state[id] = val; }
State & operator=(const State & src) {for(int i = 0; i < 3; i++) *state[i] = *src.state[i]; }
}
void fun(State * s){
State s2;
s2 = *s; // this is ok
State s1 = *s; // this is not ok apparently
}
So yeah, apparently you can't use copy operator at initialization. Anybody knows the reason for that?