如何强制调用 const find

Yve*_*ves 1 c++ stl thread-safety c++11

我用std::mapC++11编码。

我读过这个链接,它告诉我 C++11 标准保证 const 方法对容器的访问从不同的线程是安全的。

据我了解,这意味着它std::map::size()是线程安全的,因为这个函数被声明为size_type size() const noexcept;.

现在我想std::map::find线程安全地调用该函数。例如,if (mp.find(xxx) != mp.end()) {}但是,有两个版本find,一个是const,另一个是非consthttps : //en.cppreference.com/w/cpp/container/map/find

那么我怎么知道find调用的是哪个版本呢?如何强制find调用const-version以获得线程安全代码

我知道有一个 const 版本的std::map::cend(),会if (mp.find(xxx) != mp.cend()) {}按预期工作吗?

Kar*_*yan 5

你本可以使用std::as_const.

if(std::as_const(mp).find(xxx)==mp.end())
{
    //do your thing
}
Run Code Online (Sandbox Code Playgroud)