Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decltype remove const from return types for built-in types?

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.

like image 874
KnowItAllWannabe Avatar asked Aug 29 '13 04:08

KnowItAllWannabe


1 Answers

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

like image 120
James McNellis Avatar answered Sep 28 '22 12:09

James McNellis