简体   繁体   中英

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 ?

Shouldn't operator-> drill down until pair ?

The recursion of operator -> only works until you get a pointer type. 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. Once you hit that pointer, you are left accessing the members of the unique_ptr , not the pair<int, int> it points to.

You can get what you want using

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

so now you are using operator-> of unique_ptr<pair<int, int>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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