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

Typically, decltype saves a constant:

 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 returning basic types, decltype seems to discard const :

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

Why decltype discard a constant in this case? I mean the question in two ways:

  • What part of the standard does this behavior indicate?
  • What is the motivation for determining behavior in this way?

Thanks.

+8
c ++ c ++ 11 decltype
source share
1 answer

Correct behavior: decltype(makeCI()) int , not int const .

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

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

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

(In recent drafts of a C ++ language standard, such as N3690, this text has been deleted and replaced with a new text in Β§5 [expr] / 6, which states: "If the prvalue value is originally of type" cv T "," where T is unqualified unclassified, non-massive type, type of expression until parsed . "See CWG defect 1261. )

+16
source share

All Articles