Modyfying object when passed by const reference

Viewed 74

I find the below behaviour really weird, and was just the cause of a strange bug in my code. Is it considered bad to pass objects with references around as const references and then use those refs to change the object they refer to? I get that the reference doesn't change, but I would have assumed that passing the object as a const ref would make all of it's members const as well?

struct wrapr{
    int& a;
};

void mod(const wrapr& aaa){
    aaa.a = 1;
}


int main() {
  int b = 2;
  wrapr a {b};

  mod(a);
  std::cout << b;  // prints 1
  return 0;
}

EDIT:

what is weird is that if I were to declare the struct

struct wrapr{
    const int& a;
};

Then the code would not compile. I guess the mental model I had what when you pass an object by const reference, it is the same as prefixing 'const' on to all of it's member variables. Clearly this is not the case.

0 Answers
Related