Search code examples
c++dereferencedecltype

What is the type of derefenced pointer or iterator?


If I have something like this:

int a = 5;
auto* p = &a;
decltype(*p) b = 1;

I'd guess that decltype(*p) is int and not int& or const int&.

But then what about dereferencing an iterator, e.g.

std::vector<int> a { 5 };
auto it = a.begin();
decltype(*it) b = 1;

Is decltype(*it) int? But isn't the type of *it int&?

I suspect that the answer is contained in item (4) here, but I'm still confused about xvalue and prvalue.

Edit: In the original code that confused me, I must have had something equivalent to

const int a = 5;
auto* p = &a;
decltype(*p) b = 1;

and not realized that a is const, so decltype(*p) was const int& and that's why the third line was fine.


Solution

  • Both *p and *it give you an int&, which is a lvaue reference to an int. Since you have an lvalue decltype(lvalue) gives you a T&.

    That means in both code blocks b is an int& and the code wont compile as you cannot bind a prvalue (1 in this case) to a non-const lvalue reference