它->首先给出什么类型?
What type does it->first give?
考虑以下代码:
static std::unordered_map<std::string, Info> stringCollection;
auto& [it, inserted] = stringCollection.try_emplace(pString);
if (inserted) {
it->second.str = &it->first;
}
return it->second;
这一行 it->second.str = &it->first
应该复制密钥(指针)的地址 - 但我似乎无法验证是否是这种情况(找不到参考)。 it->first
基本上会给我一份副本或参考资料吗?
迭代器持有 key/value 对。所以 ->first 会给出一个 std::string 作为参考
您想删除 auto
之后的 &
因为 try_emplace
没有 return 引用:
auto [it, inserted] = stringCollection.try_emplace(pString);
在这种情况下,it
的类型是std::unordered_map<std::string, Info>::iterator
,它满足LegacyForwardIterator which implies LegacyInputIterator:
it->m
等同于 (*it).m
;
*it
returns std::iterator_traits<It>::reference
(其中 It
是 it
的类型)。
所以在你的例子中*it
的类型是std::pair<const std::string, Info>&
(一个引用),所以如果你访问它的成员first
,你会得到一个[=25=的引用] 如你所料。
考虑以下代码:
static std::unordered_map<std::string, Info> stringCollection;
auto& [it, inserted] = stringCollection.try_emplace(pString);
if (inserted) {
it->second.str = &it->first;
}
return it->second;
这一行 it->second.str = &it->first
应该复制密钥(指针)的地址 - 但我似乎无法验证是否是这种情况(找不到参考)。 it->first
基本上会给我一份副本或参考资料吗?
迭代器持有 key/value 对。所以 ->first 会给出一个 std::string 作为参考
您想删除 auto
之后的 &
因为 try_emplace
没有 return 引用:
auto [it, inserted] = stringCollection.try_emplace(pString);
在这种情况下,it
的类型是std::unordered_map<std::string, Info>::iterator
,它满足LegacyForwardIterator which implies LegacyInputIterator:
it->m
等同于(*it).m
;*it
returnsstd::iterator_traits<It>::reference
(其中It
是it
的类型)。
所以在你的例子中*it
的类型是std::pair<const std::string, Info>&
(一个引用),所以如果你访问它的成员first
,你会得到一个[=25=的引用] 如你所料。