Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 205
foraidt Avatar asked Mar 23 '09 09:03

foraidt


2 Answers

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.

like image 66
Brian R. Bondy Avatar answered Sep 21 '22 12:09

Brian R. Bondy


To me, passing a const reference for primitives is a mistake. Either you need to modify the value, and in that case you pass a non-const reference, or you just need to access the value and in that case you pass a const.

Const references should only be used for complex classes, when copying objects could be a performance problem. In the case of primitives, unless you need to modify the value of the variable you shouldn't pass a reference. The reason is that references take more computation time than non-references, since with references, the program needs to look up in a table to find the address of the object. When this look-up time is shorter than the copying time, references are an improvement.

Generally, ints and addresses have the same byte length in low-level implementations. So the time of copying an int as a return value for a function is equivalent to the time of copying an address. But in the case where an int is returned, no look up is performed, therefore performance is increased.

like image 22
Manu Avatar answered Sep 19 '22 12:09

Manu