本文介绍了c++ 11 中指针的“自动"类型分配是否需要“*"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我的变量是一个指针,如果我将它分配给auto"类型的变量,我是否指定了*"?

Given my variable being a pointer, if I assign it to a variable of "auto" type, do I specify the "*" ?

std::vector<MyClass> *getVector(); //returns populated vector
//...

std::vector<MyClass> *myvector = getVector();  //assume has n items in it
auto newvar1 = myvector;

// vs:
auto *newvar2 = myvector;

//goal is to behave like this assignment:
std::vector<MyClass> *newvar3 = getVector();

我对这个 auto 在 c++11 中的工作方式有点困惑(这是 c++11 的一个新特性,对吧?)

I'm a bit confused on how this auto works in c++11 (this is a new feature to c++11, right?)

更新:我修改了上面的内容以更好地阐明我的向量是如何真正填充到函数中的,我只是试图将返回的指针分配给一个变量.抱歉造成混乱

Update: I revised the above to better clarify how my vector is really populated in a function, and I'm just trying to assign the returned pointer to a variable. Sorry for the confusion

推荐答案

auto newvar1 = myvector;

// vs:
auto *newvar2 = myvector;

这两个都是一样的,会声明一个指向 std::vector .所以基本上你可以使用其中的任何一种.我更喜欢 auto var = getVector(),但如果你认为它强调意图(即 var 是一个指针)更好.

Both of these are the same and will declare a pointer to std::vector<MyClass> . So basically you can use any one of them. I would prefer auto var = getVector(), but you may go for auto* var = getVector() if you think it stresses the intent (that var is a pointer) better.

但是,当稍作修改时,两者之间略有不同:

However, there is slight difference between the two when modifies slightly:

auto newvar1 = myvector, newvar2 = something;

在这种情况下,newvar2 将是一个指针(并且某些东西也必须如此).

In this case, newvar2 will be a pointer (and something must be too).

auto *newvar1 = myvector, newvar2 = something;

这里,newvar2 是指针类型,例如.std::vector,并且初始化器必须足够.

Here, newvar2 is the pointee type, eg. std::vector<MyClass>, and the initializer must be adequate.

一般来说,如果初始化器不是花括号初始化器列表,编译器会像这样处理auto:

In general, if the initializer is not a braced initializer list, the compiler processes auto like this:

  1. 它生成一个人工函数模板声明,其中一个参数与声明符的形式完全相同,auto 被模板参数替换.所以对于 auto* x = ...,它使用

  1. It produces an artificial function template declaration with one argument of the exact form of the declarator, with auto replaced by the template parameter. So for auto* x = ..., it uses

template <class T> void foo(T*);

  • 它尝试解析调用 foo(initializer),并查看为 T 推导出的内容.这被替换回 auto.

  • It tries to resolve the call foo(initializer), and looks what gets deduced for T. This gets substituted back in place of auto.

    如果一个声明中有更多声明符,则对所有声明符都这样做.推导出的 T 必须对它们全部相同...

    If there are more declarators in a single declarations, this is done for all of them. The deduced T must be the same for all of them...

    这篇关于c++ 11 中指针的“自动"类型分配是否需要“*"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 09-05 08:52