带有指针容器的自动类型推导

auto type deduction with container of pointers

我不明白为什么编译器决定在第 3 个 for 循环中为迭代器 itr 使用指向 in 的指针,而不是像前 2 个循环中那样使用指向指针的指针。我尝试解析 the deduction rules 但找不到相关部分。

void foo()
{
    vector<int*> a;
    int b[] =   { 1, 2, 3 };

    for (int i = 0; i < 3; i++)
    {
        a.push_back(&b[i]);
    }
    for (vector<int*>::iterator itr = a.begin(); itr != a.end(); ++itr)
    {
        //itr is a pointer to a pointer to an int
        cout << **itr << endl;
    }
    for (auto itr = a.begin(); itr != a.end(); ++itr)
    {
        //itr is a pointer to a pointer to an int
        cout << **itr << endl;
    }
    for (auto itr : a)
    {
        //itr is a pointer to an int.  Why?
        cout << *itr << endl;
    }
}

来自 range for:

attr(optional) for ( range_declaration : range_expression ) loop_statement

...

range_declaration - a declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction

for (auto itr : a)

这里itr获取a中元素的类型,即int*.

你可以这样写:

for (auto& itr : a)

并获得对 a 中元素的引用,但无法获得指向该类型的指针。

另一方面,迭代器代表一个类似指针的实体,它指向容器的元素,这就是为什么要使用两次解引用:一次获取迭代器指向的元素的值并具有int* 的类型,第二次从 int*.

获取实际的 int