diff --git a/base/include/safe_map.h b/base/include/safe_map.h index cf010005208079860d86496329349e930d9e9e66..8cd8a35e2dd9c097b5bf859a7dd929059e2df7a9 100644 --- a/base/include/safe_map.h +++ b/base/include/safe_map.h @@ -33,14 +33,17 @@ public: SafeMap(const SafeMap& rhs) { - map_ = rhs.map_; + operator=(rhs); } SafeMap& operator=(const SafeMap& rhs) { - if (&rhs != this) { - map_ = rhs.map_; + if (this == &rhs) { + return *this; } + auto tmp = rhs.Clone(); + std::lock_guard lock(mutex_); + map_ = std::move(tmp); return *this; } @@ -211,8 +214,14 @@ public: } private: - std::mutex mutex_; + mutable std::mutex mutex_; std::map map_; + + std::map Clone() const noexcept + { + std::lock_guard lock(mutex_); + return map_; + } }; } // namespace OHOS