Passing an object by reference is an easier, faster and safer way to pass an address to it. But for most compilers, it's all the same: references are really pointers.
Now what about basic types like int
? Passing an address to an int
and using it inside a function would be slower than passing it by copy, because the pointer needs to be dereferenced before use.
How do modern compiler handle, this?
int foo(const int & i)
{
cout << i; // Do whatever read-only with i.
}
May I trust them to compile this into this?
int foo(const int i)
{
cout << i;
}
By the way, in some cases it could even be faster to pass both i
and &i
, then use i
for reading, and *i
for writing.
int foo(const int i, int * ptr_i)
{
cout << i; // no dereferencement, therefore faster (?)
// many more read-only operations with i.
*ptr_i = 123;
}
May I trust them to compile this into this?
Yes You can.[The Yes here means differently, Please read Edit section, Which clarify's]
int foo(const int & i)
Tells the compiler that i
is an reference to type constant integer.
The compiler may perform optimizations but they are only allowed to perform optimizations following the As-If Rule. So you can be assured that for your program the behavior of the above will be as good as(the const
qualifier will be respected):
int foo(const int i)
As-If Rule:
The C++ standard allows a compiler to perform any optimization, as long as the resulting executable exhibits the same observable behaviour as if all the requirements of the standard have been fulfilled.
For Standerdese fans:
C++03 1.9 "Program execution:
conforming implementations are required to emulate (only) the observable behavior of the abstract machine.
And the Foot-Note says:
This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.
EDIT:
Since there is some confusion about the answer let me clarify:
Optimizations cannot be enforced on the compiler.So How compiler interprets it depends on the compiler.The important thing is the observable behavior of the program will not change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With