0

I've recently noticed that the const keyword on some code examples shifted in the middle (from respectable blog sites), something like this:

X(X const& that) { .../... }

X& operator=(X const& other) { .../... }

Is this equivalent to this more familiar syntax?

X(const X& that) { .../... }

X& operator=(const X& other) { .../... }

What is the purpose of switching 'const' that way?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
John Difool
  • 5,572
  • 5
  • 45
  • 80
  • 1
    They are equivalent. It's simply a matter of taste. – Lingxi Jan 17 '16 at 06:33
  • Relevant: [C++: const reference, before vs after type-specifier](http://stackoverflow.com/questions/3694630/c-const-reference-before-vs-after-type-specifier) – cpplearner Jan 17 '16 at 06:41

2 Answers2

1

1) It doesn't matter where to put const: const int & == int const &

2) Why? It is mnemonic rule.

int * const - constant pointer (const after *)

int const * - pointer to the constant value (const after int).

So, its for consistency.

SashaMN
  • 708
  • 5
  • 16
0

Is this equivalent to this more familiar syntax?

Yes, both syntaxes here are equivalent.

X(X const& x)
X(const X& x)

This says that x aliases an object of type X, but that the object cannot be changed using x. (It can still be modified if you use some non-const alias, pointer, etc.)

You should read it from right-to-left: x is an alias (or reference) to an object of type X that is const.

I'd also recommend reading C++ FAQ: Const Correctness

code_dredd
  • 5,915
  • 1
  • 25
  • 53