lundi 22 janvier 2018

Assignment with struct function-object (C++)

Suppose we have the following struct that is also "callable" as a function object.

struct MultBy3
{
  MultBy3() : struct_val(3) {}
  MultBy3(int x) : struct_val(x*3) { x = x*3; }
  MultBy3(MultBy3 &b) : struct_val(b.struct_val*3){ 
    b.struct_val = b.struct_val*3;
  }
  int struct_val ;
};

I started playing with this in main()to get some intuition. When I tried something really simple:

int main(){
    MultBy3 a;    // has a.struct_val = 3
    MultBy3 b;    // has b.struct_val = 3
    b = a;
    std::cout << a.struct_val << b.struct_val << std::endl;
}

it prints out 33 to the console (as expected), but when I initialize struct b slightly differently,

int main(){
    MultBy3 a;     // has a.struct_val = 3
    MultBy3 b = a; 
    std::cout << a.struct_val << b.struct_val << std::endl;
}

I get that a.struct_val = 9 and b.struct_val = 9. I know this has to do with

MultBy3(MultBy3 &b) : struct_val(b.struct_val*3){ 
  b.struct_val = b.struct_val*3;
}

because when I comment that part out in MultBy3, the same code prints outputs 33. This would make sense to me if the line MultBy3 b = a; were instead MultBy3 b(a);, because then a is passed by reference, so setting a.struct_val = a.struct_val * 3 lasts outside of the "function call" (and b.struct_val = a.struct_val * 3 = 3*3 = 9). However, I am unsure why the initialization MultBy3 b = a; has that behavior, especially when MultBy3 b; b = a acts differently.

Aucun commentaire:

Enregistrer un commentaire