简体   繁体   English

如果像这样使用 c++ std::unordered_map 会有风险吗?

[英]Does it risk if use c++ std::unordered_map like this?

Does it risk if use c++ std::unordered_map like this?如果像这样使用 c++ std::unordered_map 会有风险吗?

   std::unordered_map<std::string, std::unordered_set<std::shared_ptr<SomeType>>> _some_map;
   ...
   void init() {
       auto item = std::make_shared<SomeType>();
       _some_map["circle"].insert(item);
   }

_some_map is a member variable. _some_map 是一个成员变量。 init() function can be called only once, so insert is thread-safe. init() 函数只能调用一次,因此 insert 是线程安全的。 After initialization, the map will be read only in multi-thread.初始化后,地图将在多线程中只读。 I think it is thread-safe too.我认为它也是线程安全的。

I'm not sure if I can use insert like this.我不确定我是否可以像这样使用插入。 Because it will make a unordered_set and a pair when there is no val of key "circle".因为当没有键“circle”的val时,它会生成一个unordered_set和一个pair。 The code works normally.代码正常工作。 Just want to make sure it is without potential risk.只是想确保它没有潜在风险。

(I am not good at English writing. ) (我不擅长英文写作。)

Thank you.谢谢你。

I'm not sure if I can use insert like this.我不确定我是否可以像这样使用插入。

Yes, you can, because operator[]是的,你可以,因为operator[]

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.返回对映射到与 key 等效的键的值的引用,如果这样的键不存在,则执行插入。

Your value_type is std::unordered_set which is default constructible, so there is no problem.您的value_typestd::unordered_set ,它是默认可构造的,所以没有问题。

After initialization, the map will be read only in multi-thread初始化后,地图将在多线程中只读

Here also you are safe, because according to the containers documentation在这里你也是安全的,因为根据容器文档

All const member functions can be called concurrently by different threads on the same container.所有 const 成员函数都可以由同一容器上的不同线程并发调用。

so if you are only reading the values without modifying them, it is OK.因此,如果您只是读取值而不修改它们,那没关系。 You could even perform write operations if you could guarantee that different threads are accessing different elements in your container.如果您可以保证不同的线程正在访问容器中的不同元素,您甚至可以执行写操作。

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

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