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?
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.
'auto' lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With