Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are cv-qualifiers allowed on decltype(auto) variables?

The standard states that

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone.

decltype(auto)*x7d = &i; // error, declared type is not plain decltype(auto)

It is not clear whether cv-qualifiers are still allowed though. It would make sense if they are allowed. Compilers seem to disagree on this matter. The following code is accepted by g++ but rejected by clang++, vc++ does not seem to support decltype(auto) variables at all:

int main()
{
    const decltype(auto) sz_text{"test"};
}
like image 701
user7860670 Avatar asked Jan 15 '18 12:01

user7860670


People also ask

What is cv qualified?

The declaration of an object that is not preceded by const and/or volatile is a cv-unqualified type. On the other hand, the declaration of an object that is preceded by const and/or volatile is a cv-qualified type. If an object is declared const, the value in its location cannot be changed.

How to initialize auto variable in C++?

You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.

What's the auto keyword good for?

The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.

What is the auto data type in C++?

The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.


1 Answers

To answer that, we need to quote the previous paragraph, which specifies what T is. In this case, [dcl.type.auto.deduct]/2 says (emphasis mine):

A type T containing a placeholder type, and a corresponding initializer e, are determined as follows:

  • for a variable declared with a type that contains a placeholder type, T is the declared type of the variable and e is the initializer. If the initialization is direct-list-initialization, the initializer shall be a braced-init-list containing only a single assignment-expression and e is the assignment-expression;

In this case, T is the whole declared type of sz_text, cv-qualifiers and all. And the paragraph you quoted is quite clear that if it contains decltype(auto) as placeholder, it must be that and nothing more.

So a GCC bug. And an already reported one.

like image 196
StoryTeller - Unslander Monica Avatar answered Oct 06 '22 02:10

StoryTeller - Unslander Monica