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 &
It is valid code, because a
is not const
. A const
reference means you cannot modify the refered-to object via the reference.
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".
As a reference is just another name to a variable and not the object itself, yes in the snippet you show it can be thought as a read-only reference. The code provided with the reference can only access it but it does not guarantee that the object itself won't be changed in another place of your program.