...
Inexperienced programmers are therefore tempted to write:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char &const p; |
instead of:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char const& p; |
If the compiler does not complain of the const reference, the program might be compiled and run and produce surprising results. This is because the first form still allows you to change the character pointed at by p, while the second does not.
...
In this code, the character, which happens to point to a string literal, is accessed by a reference. The reference itself is const, but the pointed-to data is not. Consequently it is possible to modify the data via the reference.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char c = 'c'; char &const p = c; p = 'p'; cout << c << endl; |
...
If constant reference is required (and the data may be modified via this variable), instead of using a const reference, one can use a const pointer:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char c = 'c'; char *const p = &c; *p = 'p'; // causes compiler error cout << c << endl; |
...
References are still safer than pointers, so a reference to a const value is the best solution when feasible.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char c = 'c'; const char& p = c; *p = 'p'; // causes compiler error cout << c << endl; |
...