将std::mutex放入std::map中

参考:c++ – Map of mutex c++11 – Stack Overflow
std::mutex不好放进map的主要缘由是:

can t create map from string to mutex, because there is no copy constructor in std::mutex

解决办法一:

Replace mutexCache.insert(new std::unique_ptr<std::mutex>) 
mutexCache.emplace(key, new std::mutex);
mutexCache.emplace(key, std::make_unique<std::mutex>());

解决办法二:

TL;DR: just use operator [] like std::map<std::string, std::mutex> map; map[filename];

Why do you need to use an std::unique_ptr in the first place?

I had the same problem when I had to create an std::map of std::mutex objects. The issue is that std::mutex is neither copyable nor movable, so I needed to construct it “in place”.

I couldn t just use emplace because it doesn t work directly for default-constructed values. There is an option to use std::piecewise_construct like that:

map.emplace(std::piecewise_construct, std::make_tuple(key), std::make_tuple());

but it s IMO complicated and less readable.
My solution is much simpler – just use the operator[] – it will create the value using its default constructor and return a reference to it. Or it will just find and return a reference to the already existing item without creating a new one.

std::map<std::string, std::mutex> map;
std::mutex& GetMutexForFile(const std::string& filename)
{
    return map[filename]; // constructs it inside the map if doesn t exist
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
就一丢丢lia的头像 - 鹿快
评论 抢沙发

请登录后发表评论

    暂无评论内容