Question

As a general rule, decltype preserves constness:

const int ci = 0;
decltype(ci)  x;         // x is const int
x = 5;                   // error--x is const

class Gadget{}:

const Gadget makeCG();         // factory

decltype(makeCG()) y1, y2;     // y1 and y2 are const Gadgets
y1 = y2;                       // error--y1 is const

But for const return types that return fundamental types, decltype seems to throw const away:

const int makeCI();            // factory

decltype(makeCI()) z;          // z is NOT const
z = 5;                         // okay

Why does decltype discard constness in this case? I mean the question in two ways:

  1. What part of the standard specifies this behavior?
  2. What is the motivation for specifying the behavior this way?

Thanks.

Was it helpful?

Solution

The behavior you observe is correct: decltype(makeCI()) is int, not int const.

The makeCI() function call expression is a prvalue expression. Per C++11 §3.10[basic.lval]/4:

Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types.

The term "cv-qualification" refers to const- and volatile-qualification. int is not a class type, so the type of the rvalue expression makeCI() is int and it is not const-qualified.

(In recent drafts of the C++ language standard, e.g. N3690, this text has been removed and replaced by new text at §5[expr]/6, which states, "If a prvalue initially has the type "cv T," where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis." See CWG defect 1261 for details.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top