简体   繁体   中英

position of const for pointer or reference

For simple types, position of const to the left of * or & has the same effects. That is:

const type *

is equivalent to

type const *

(so is reference). For example:

const double pi = 3.14159;
const const double * pip1 = π
const double const * pip2 = π
const double & pir1 = pi;
double const & pir2 = pi;

pip1 and pip2, and pir1 and pir2, are both the same and the compiler accepts them without any error.

But the situation changes when it comes to more complex types. For the following code:

const std::vector<std::string> vs(10);
const std::string * const & ppp = &vs[0];

where type is const std::string * , I cannot write the definition of ppp as

const const std::string * & ppp = &vw[0];

because compiler utters an error:

error C2440: 'initializing': cannot convert from 'const std::basic_string< char,std::char_traits,std::allocator> *' to 'const std::string *&'

So my question is: why I cannot put const of & before the const of * in this case? I tried to add parentheses to help compiler work but only produced more errors. Thank you.

PS: I am working on Visual Studio 2015 on Windows 10.

But the situation changes when it comes to more complex types

No, the situation is exactly the same.

const applies to the left, unless there's nothing there, in which case it applies to the right.

There is absolutely no way for the compiler (or anyone else) to know what you meant by const const std::string * & ppp .

Your example of const const double * pip1 = &pi is illegal too, and doesn't compile with GCC ; if Visual Studio accepts it, that's some weird non-standard extension — to understand it (and how to use it in the case you described), you'll have to refer to the Microsoft documentation. It would be better to avoid such antics, though.

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