The question can be formulated by example as following: is this snippet of code valid?
int a = 1;
const int& ca = a;
++a; //< Q: Is this valid?
cout &
In this particular case, all you are doing is creating a REFERENCE that is const
- meaning that ca
can't modify the value it refers to (a
in this case).
A common usage is to pass a const reference to a function:
void foo(const int& cr)
{
... use cr ...
}
This indicates that although the value is a reference, the function foo
does not alter the value in cr
. It is perfectly valid to call this function with a modifiable int
variable, or even something that can't be referenced (for example foo(4);
- the value 4 is just a constant, so can't really be used as a reference - the compiler will "fix" this by creating a temporary int variable, and pass the reference to that).
Of course, this is more commonly used with more complex types than int
- for example std::string
or std::vector
. The main reason in this case is to avoid the value being copied, rather than "I want a reference".