简体   繁体   English

为什么 std::vector::iterator::operator-> 只向下钻取一层?

[英]Why does std::vector::iterator::operator-> only drill down one level?

This code fails to compile:此代码无法编译:

void foo(vector<unique_ptr<pair<int, int>>> bar)
{
    bar.begin()->first;
}

What's the problem here?这里有什么问题? Shouldn't operator-> drill down until pair ?不应该operator->向下钻取直到pair吗?

Shouldn't operator-> drill down until pair ?不应该operator->向下钻取直到pair吗?

The recursion of operator -> only works until you get a pointer type. operator ->的递归仅在您获得指针类型之前有效。 Once that happens the recursion stops and you access what that pointer points to.一旦发生这种情况,递归就会停止,您可以访问该指针指向的内容。 In this case std::vector::iterator::operator-> returns a unique_ptr<pair<int, int>>* as that pointer type of the element in the vector.在这种情况下, std::vector::iterator::operator->返回一个unique_ptr<pair<int, int>>*作为向量中元素的指针类型。 Once you hit that pointer, you are left accessing the members of the unique_ptr , not the pair<int, int> it points to.一旦你点击了那个指针,你就只能访问unique_ptr的成员,而不是它指向的pair<int, int>

You can get what you want using你可以得到你想要的使用

(*bar.begin())->first;

so now you are using operator-> of unique_ptr<pair<int, int>> .所以现在您使用的是operator-> of unique_ptr<pair<int, int>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM