I know that where possible you should use the const keyword when passing parameters around by reference or by pointer for readability reasons. Is there any optimizations that the compiler can do if I specify that an argument is constant?
There could be a few cases:
Function parameters:
Constant reference:
void foo(const SomeClass& obj)
Constant SomeClass object:
void foo(const SomeClass* pObj)
And constant pointer to SomeClass:
void foo(SomeClass* const pObj)
Variable declarations:
const int i = 1234
Function declarations:
const char* foo()
What kind of compiler optimizations each one offers (if any)?
The following is a paraphrase of this article.
Case 1:
When you declare a
constin your program,Compiler can optimize away this
constby not providing storage for this variable; instead it can be added to the symbol table. So a subsequent read just needs indirection into the symbol table rather than instructions to fetch value from memory.Note: If you do something like:
Then this would force compiler to allocate space for
x. So, that degree of optimization is not possible for this case.In terms of function parameters
constmeans that parameter is not modified in the function. As far as I know, there's no substantial performance gain for usingconst; rather it's a means to ensure correctness.Case 2:
No, as argument is already passed by reference.
No, as both
xandsomeYlive outside its scope and come from and/or are given to the outside world. Even ifsomeYis dynamically allocated on the fly withinf()itself, it and its ownership are given up to the caller.Even when you call a const member function, the compiler can't assume that the bits of object
xor objectsomeYwon't be changed. Further, there are additional problems (unless the compiler performs global optimization): The compiler also may not know for sure that no other code might have a non-const reference that aliases the same object asxand/orsomeY, and whether any such non-const references to the same object might get used incidentally during the execution off();and the compiler may not even know whether the real objects, to whichxandsomeYare merely references, were actually declared const in the first place.Case 3:
Yes because the compiler knows that
ztruly is a const object, it could perform some useful optimizations even without global analysis. For example, if the body off()contains a call likeg( &z ), the compiler can be sure that the non-mutable parts ofzdo not change during the call tog().