B
Ben Voigt
Sorry about not compile-testing.
Here is an example that may work better for you:
/* in one compilation unit */
namespace { std::vector<int> v; }
void stuffit(int& n)
{
v.push_back(n);
}
/* in another compilation unit, assuming that the proper prototype for
stuffit is available */
int main()
{
for( int i = 0; i < 4; i++ ) {
stuffit(i);
}
return 0;
}
Without "const", no optimizations are possible. With "const int& n", the
compiler can fully unroll the loop and eliminate i. Yes, I know that
passing an int by const reference in this case is silly, but it could easily
be a large data structure, and stuffit could be an arbitrary level of
complexity.
Or:
void demo(int i)
{
int a[10];
for( int j = 0; j < 10000; j++ )
{
a[13 * i % 7 + 3] += j;
stuffit(i);
}
}
With "const int& n", the compiler can determine that i is unchanging for the
duration of the loop, and by extension, the pointer a + 13 * i % 7 + 3 can
be pre-computed (and in fact the entire addition operation could be
pre-evaluated as 10000 * 10001 / 2 => 50005000). Without "const", aliasing
analysis reveals that i can change, therefore the computation must be
executed inside the loop, with little opportunity for optimization.
And the const on a member function is equivalent to changing constness of
the 'this' parameter, so all the above applies.
Here is an example that may work better for you:
/* in one compilation unit */
namespace { std::vector<int> v; }
void stuffit(int& n)
{
v.push_back(n);
}
/* in another compilation unit, assuming that the proper prototype for
stuffit is available */
int main()
{
for( int i = 0; i < 4; i++ ) {
stuffit(i);
}
return 0;
}
Without "const", no optimizations are possible. With "const int& n", the
compiler can fully unroll the loop and eliminate i. Yes, I know that
passing an int by const reference in this case is silly, but it could easily
be a large data structure, and stuffit could be an arbitrary level of
complexity.
Or:
void demo(int i)
{
int a[10];
for( int j = 0; j < 10000; j++ )
{
a[13 * i % 7 + 3] += j;
stuffit(i);
}
}
With "const int& n", the compiler can determine that i is unchanging for the
duration of the loop, and by extension, the pointer a + 13 * i % 7 + 3 can
be pre-computed (and in fact the entire addition operation could be
pre-evaluated as 10000 * 10001 / 2 => 50005000). Without "const", aliasing
analysis reveals that i can change, therefore the computation must be
executed inside the loop, with little opportunity for optimization.
And the const on a member function is equivalent to changing constness of
the 'this' parameter, so all the above applies.