Using const and decltype with a pointer variable
c++, c++11
Solution
`const decltype(p1) p2` means `int* const p2` .
This means that you cannot change `p2`, but you may change the things being pointed to.
`const T` always applies const to the so-called "top level" of `T`. When `T` is a composite type (that is, a type built up from the basic set of types) then you will have to jump through hoops if you want to apply `const` to the lower levels.
When T is `int *` , adding top level const would give `int * const`. The `*` demarcates a level; to get at the stuff below the `*` you have to manually remove the `*`, apply `const`, then put the `*` back.
A possible solution is:
const std::remove_pointer<decltype(p1)>::type *p2 = new int(100);
Problem
The following code allows me to change the value at *p2 even though p2 is declared with const. ``` int *p1; const decltype(p1) p2 = new int(100); *p2 = 200; cout << "*p2: " << *p2 << endl; // Outputs *p2: 200 ``` However, if I use "int *" instead of "decltype(p1)", then the compiler flags an error. ``` const int * p2 = new int(100); *p2 = 200; cout << "*p2: " << *p2 << endl; error: assignment of read-only location ‘* p2’ *p2 = 200; ^ ``` I am using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. Does decltype ignore const specifier when applied on pointer variable?