decltype and pointers

Asked

Viewed 52 times

1

I wanted to know why, when I use decltype(*Pointer) - using a pointer - it defines the type of the variable as reference, example:

int i = 42, *p = &i;
decltype(*p) c = i;

What I want you to understand in my question is this: Now c is a reference (linked to i), but why is it a reference and not an entire plan? I’m reading Cpp Primer 5th. Edition (p. 110) says this and does not understand it.

1 answer

1

The rules of the specifier decltype are here: https://en.cppreference.com/w/cpp/language/decltype

Your case falls into any expression (third item), because *p is not a id-Expression, neither a class membership access, and yes any expression.

  1. If the argument is any other Expression of type T, and

    a. if the value Category of Expression is xvalue, then decltype yields T&&;

    b. if the value Category of Expression is lvalue, then decltype yields T&;

    c. if the value Category of Expression is prvalue, then decltype yields T.

The value category of the expression *p (indirect expression) is defined as a lvalue:

The following Expressions are lvalue Expressions:

  • *p, the built-in indirection Expression;

So the kind where decltype(*p) results comes from rule 3.b.: if the value Category of Expression is lvalue, then decltype yields T&, where T is the type of expression *p, which in that case is int. Replacing, we have int& as the resulting type.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.