Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Inexperienced programmers are therefore tempted to write:

Code Block
bgColor#ffcccc
langcpp
  char &const p;

instead of:

Code Block
bgColor#ccccff
langcpp
  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
bgColor#ffcccc
langcpp
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
bgColor#ccccff
langcpp
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
bgColor#ccccff
langcpp
char c = 'c';
const char& p = c;
*p = 'p'; // causes compiler error
cout << c << endl;

...