May a compiler optimize a reference to constant parameter to constant value?
Consider following function:
void func(const char & input){
//do something
}
Apparently it makes sense for the parameter to be constant开发者_C百科 value not reference to constant regarding size of the char type, Now may a compiler optimize that to constant value so that it'll be the same as following ?
void func(const char input){
//do something
}
No. This is not equivalent. In the first case, input can still change, e.g. if it's a reference to a variable that's modified by another thread.
Like someone stated, but was sadly downvoted (not sure why he did delete his answer), the compiler can do any and everything as long as the observable behavior is the same as if it did not do anything different.
It's self-expanatory that if your function writes into the reference, and a global variable was passed as argument to the function and the global was later printed after the function returns, or anything else fancy is done, then if the compiler would change the parameter passing convention, it's more difficult for the compiler to prove you still get the same observable behavior. If the compiler can't prove it, it can't do the desired optimization.
So whatever further question comes up, just think "it can do anything as long as I won't notice it".
As noted, not in general. But what the compiler can do is inline the entire function call. And if the parameter supplied is a compile time constant, it can do lots of interesting optimizations.
精彩评论