Search code examples
c++c++11decltypervaluelvalue

If I apply decltype to an expresstion that yields an rvalue, do I always get a pointer? C++


I know that if I apply decltype to p, where p is an int*, decltype(*p) is int&. And decltype(&p) is int**.

A reference being an rvalue, do I always get a pointer when applying decltype to an rvalue?


Solution

  • decltype applied to...

    • a prvalue expression gives a non-reference type,
    • an xvalue expression gives an rvalue reference type, and
    • an lvalue expression gives an lvalue reference type.

    (There is an exception for id-expressions that I won't go into. Just consider "expression" to mean "any expression other than an id-expression" for the purpose of this answer.)

    In all cases, the underlying type of the decltype type is the type of the expression.

    To put this in code, let U be an object type. Then:

    • With U f();, decltype(f()) is U.
    • With U& f();, decltype(f()) is U&.
    • With U&& f();, decltype(f()) is U&&.

    In your example, *p is an lvalue of type int, so decltype(*p) is int&, and &p is a prvalue of type int**, so decltype(&p) is int**.