2

Setting aside the main reason for marking parameters as const - so you can't alter the referenced object by mistake - it is sometimes suggested this will be faster because the compiler knows the referenced object won't be modified.

However, is this actually likely to be true in a modern C++ compiler - and is the saving non-significant compared to the overhead of calling a method?

If so can someone explain at a lower-level what the differences would be, i.e. how the compiler can behave differently - and perhaps give a concrete example where doing this would make a non-trivial difference?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

2 Answers2

2

it is sometimes suggested this will be faster because the compiler knows the referenced object won't be modified.

If you have a const reference r, then the compiler only knows that the referenced object cannot be changed through r. But since const references also bind to mutable objects, const references aren't particularly helpful with regards to optimizations. Consider this classic counter-example:

void foo(const int& a, int& b)
{
    std::cout << a*a << '\n';
    ++b;
    std::cout << a*a << '\n';
}

Will this print the same number twice, or two different numbers? If a and b denote that same object, you will get two different numbers, even though we never modify a directly inside the function!

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

Modern compilers are smart enough to see if a variable is going to be modified or not even if you don't specify it as const. For example, I just checked the assembler output of this code:

void foo( int & a )
{
    std::cout << a;
}

int main()
{
    int a = 0;
    foo(a);
}

with the a parameter being int & and const int &, and unsurprisingly the asm output was exactly the same in both cases.

In case of using a (const) reference vs passing by value, however, there will be a considerable difference. So use const for yourself and your colleagues, not for the compiler.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105