You ask,
“What are the possible cases when we cannot pass a variable by reference?”
With C++11 there are two main such cases (maybe a few more that I failed to think of):
In the latter case one could, conceivably, pass a reference to the array's first item, but then inside the function the code would just have to take the address in order to get back the array-ness, and the formal type would not just be impractical in this way, but also extremely misleading.
Also, to my surprise Visual C++ 11.0 (the compiler shipped with Visual Studio 2012) compiles the following:
#include <iostream>
using namespace std;
void foo( int const (&a)[] )
{
for( auto p = &a[0]; *p != 0; ++p )
{
wcout << *p << endl;
}
}
extern int const data[];
int main( int argc )
{
foo( data );
}
int const data[] = {1, 2, 3, 4, 5, 0};
However, MinGW g++ 4.7.1 rejects it, as it should!
One case that did exist in C++03, but no longer exists in C++11, was that in C++03 a temporary object passed to a reference to const
had to have an accessible copy constructor. That was because in C++03 the compiler was allowed to make any number of copies. In C++11 the reference has to be bound directly when that's possible.
One case that on closer inspection is a non-case is when you need to express the possibility of “does not refer to an object” like a nullpointer.
For example,
void foo( int const* pValue = 0 ) { if( pValue != 0 ) { ... } }
But there are workarounds, including the one of overloading foo
:
void foo( int const& value ) { ... }
void foo() {}