C++中关于auto关键字的困惑

Confusion about auto keyword in C++

我对以下代码感到困惑:

#include <iostream>
using namespace std;

int *foo()
{
   //Operation
}

int main ()
{
        auto int ret = foo();
}

我在GCC下编译了上面的代码,但是出现了如下错误:

error: two or more data types in declaration of 'ret'
         auto int ret = foo();

但是,如果我删除 int 类型,就像这样:

auto ret = foo();

然后运行成功

auto是一个存储class并且int是一个数据类型,那么为什么我在第一种情况下会得到错误 "two or more data types"?

auto 不是存储 class(自 C++11 起不再是)C++11 引入了关键字,允许编译器推断您声明的变量所需的类型。

所以基本上做 auto int myVarstring double myVar2bool long myVar3[=30 一样无效=]...变量只能定义一种数据类型,在您的情况下,关键字 auto 就是这样...

如何摆脱错误:

删除int类型,只使用auto,这样做会让编译器*AUTO** *自动推断变量的类型 **ret 正是 foo() returns :) 和蔼可亲!

auto ret = foo();

来自 doc

For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14). for non-type template parameters, specifies that the type will be deduced from the argument

auto 不是存储 class。它曾经是,在 C++11 之前。但它完全没用,所以关键字被重新用于允许自动类型推断。所以当你说:

auto int ret = foo();

您基本上是在将对象声明为具有 2 种类型(或者可能是同一类型两次),这是一个错误。当你说:

auto ret = foo();

ret 的类型由函数 foo returns 决定,在本例中为 int*

你写道:

auto is a storage class

但在 C++11 (or later). The auto keyword has been reused for something completely different (some limited kind of type inference 中不再如此。以前的 C++03 或 C99 auto 存储 class 现在(在 C++11 中)总是隐式的,应该 使用 auto关键字。

(如果你喜欢类型推断,C++11做的不是很好,但C++14或C++17在这方面有进步;Ocaml有更强大和有趣 Hindley-Milner type inference 更 "global";这就是我写 "some limited kind")

的原因

auto is a storage class

在 C++11 之前是这样,但现在不是了。

从C++11开始,这个词的含义发生了变化。它现在用于自动推断类型。参见 http://www.stroustrup.com/C++11FAQ.html#auto

Why in first case I got an error "two or more data types"?

通过使用

auto int ret = foo();

您正在尝试为 ret 指定两种类型 -- 一种是推断的,另一种是明确指定的。

如果要使用明确指定的类型,可以使用:

int ret = *foo(); // Since foo() returns a pointer.

int* ret = foo();

或者您可以让编译器使用以下方法推断类型:

auto ret = foo();