简体   繁体   中英

Copy ctor and copy assignment operator const keyword position

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM