Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const and decltype with a pointer variable

Tags:

c++

c++11

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?

like image 882
Ahmed Khurshid Avatar asked Feb 18 '15 03:02

Ahmed Khurshid


People also ask

What does decltype do in C++?

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.

What is the difference between auto and decltype in C++?

'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.

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.


1 Answers

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);
like image 102
M.M Avatar answered Nov 15 '22 06:11

M.M