What is the use of passing const references to primitive types?

foraidt picture foraidt · Mar 23, 2009 · Viewed 7.6k times · Source

In a project I maintain, I see a lot of code like this for simple get/set methods

const int & MyClass::getFoo() { return m_foo; }

void MyClass::setFoo(const int & foo) { m_foo = foo; }

What is the point in doing that instead of the following?

int MyClass::getFoo() { return m_foo; }  // Removed 'const' and '&' 

void MyClass::setFoo(const int foo) { m_foo = foo; }  // Removed '&'

Passing a reference to a primitive type should require the same (or more) effort as passing the type's value itself, right?
It's just a number after all...
Is this just some attempted micro-optimization or is there a true benefit?

Answer

Brian R. Bondy picture Brian R. Bondy · Mar 23, 2009

The difference is that if you get that result into a reference yourself you can track the changes of the integer member variable in your own variable name without recalling the function.

const &int x = myObject.getFoo();
cout<<x<<endl;
//...
cout<<x<<endl;//x might have changed

It's probably not the best design choice, and it's very dangerous to return a reference (const or not), in case a variable that gets freed from scope is returned. So if you return a reference, be careful to be sure it is not a variable that goes out of scope.

There is a slight difference for the modifier too, but again probably not something that is worth doing or that was intended.

void test1(int x)
{
  cout<<x<<endl;//prints 1
}

void test2(const int &x)
{
  cout<<x<<endl;//prints 1 or something else possibly, another thread could have changed x
}

int main(int argc, char**argv)
{
  int x = 1;
  test1(x);
  //...
  test2(x);
  return 0;
}

So the end result is that you obtain changes even after the parameters are passed.