确认std::unordered_set元素值指针在容器非删除修改后是否有效
指向
std::unordered_set容器中存储数据的引用和指针仅会在删除对应元素时失效,即使对应的迭代器失效也是如此。
问题确认
我希望确认自己对指向std::unordered_set中存储数据的指针有效性的理解是否正确。根据我的研究,即使后续对容器(即uset)进行修改(删除操作除外),指针(即str_a)仍然有效。
感谢您的解答
#include <iostream> #include <unordered_set> #include <memory> #include <string> int main() { std::unordered_set<std::unique_ptr<std::string>> uset{}; // 插入第一个元素 // auto [iter_a, inserted_a] = uset.emplace(std::make_unique<std::string>("hello_a")); // 保存指向第一个插入元素的指针 // const auto str_a = iter_a->get(); if (inserted_a) { std::cout << str_a->c_str() << ": " << str_a->size() << std::endl; } // 插入第二个元素 // auto [iter_b, inserted_b] = uset.emplace(std::make_unique<std::string>("hello_world_b")); const auto str_b = iter_b->get(); if (inserted_b) { std::cout << str_b->c_str() << ": " << str_b->size() << std::endl; } // 修改unordered_set后,指向第一个插入元素的指针仍然有效 // std::cout << str_a->c_str() << ": " << str_a->size() << std::endl; return 0; }
程序输出
hello_a: 7 hello_world_b: 13 hello_a: 7
解答
你的理解完全正确。std::unordered_set的特性就是:只要目标元素没有被从容器中删除,指向该元素的指针和引用就始终保持有效——哪怕容器因为插入、扩容等操作导致迭代器失效,这些指针和引用也不受影响。
从你的代码运行结果也能验证这一点:插入第二个元素后,原本指向第一个元素的str_a依然能正确访问并输出内容,说明指针有效性未受容器修改操作的影响。
内容的提问来源于stack exchange,提问作者q0987
相关产品推荐
相关产品推荐

