【发布时间】:2020-07-16 00:51:53
【问题描述】:
我有时会有这样的课程:
class HasMutexLockedCache {
private:
SomeType m_regularData;
mutable std::mutex m_mutex;
mutable std::optaional<T> m_cache;
// Etc.
public:
const m_regularData& getData() const { return m_regularData; }
const T& getExpensiveResult() const {
std::scoped_lock lock(m_mutex);
if (!m_cache) {
m_cache = expensiveFunction();
}
return m_cache;
}
HasMutexLockedCache(const HasMutexLockedCache& other)
: m_regularData(other.m_regularData)
{
std::scoped_lock lock(other.m_mutex);
// I figure we don't have to lock this->m_mutex because
// we are in the c'tor and so nobody else could possibly
// be messing with m_cache.
m_cache = other.m_cache;
}
HasMutexLockedCache(HasMutexLockedCache&& other)
: m_regularData(std::move(other.m_regularData))
{
// What here?
}
HasMutexLockedCache& operator=(HasMutexLockedCache&& other) {
m_regularData = std::move(other.m_regularData);
// Bonus points: What here? Lock both mutexes? One?
// Only lock this->m_mutex depending on how we
// document thread safety?
}
};
我的问题:HasMutexLockedCache(HasMutexLockedCache&& other) 中有什么内容(HasMutexLockedCache& operator=(HasMutexLockedCache&& other) 中也是如此?我认为我们不需要锁定other.m_mutex,因为other 是一个右值引用,我们知道没有其他人可以看到它,就像我们不必将 this->m_mutex 锁定在 c'tor 中一样。但是,我需要一些指导。这里的最佳做法是什么?我们应该锁定 other.m_mutex 吗?
【问题讨论】:
标签: c++ move-semantics