工作情况:为什么我们可以锁定一个const对象中定义的互斥锁?
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
public:
threadsafe_queue()
{}
threadsafe_queue(const threadsafe_queue& other)
{
std::lock_guard<std::mutex> lk(other.mut);
data_queue=other.data_queue;
}
};
情况下应该会失败:注意没有mutable
上std::mutex mut;
template<typename T>
class threadsafe_queue
{
private:
std::mutex mut;
std::queue<T> data_queue;
public:
threadsafe_queue()
{}
threadsafe_queue(const threadsafe_queue& other)
{
std::lock_guard<std::mutex> lk(other.mut);
data_queue=other.data_queue;
}
};
我曾尝试上面列出的这两种情况下,他们编译没有问题。我在内部假设lock_guard调用mutex :: lock函数,它本身不是一个const函数。
问题>为什么我们可以在复制构造函数中锁定const对象的互斥量?
肯定'可变'是这里的关键? –
@OliverCharlesworth:看看第二个版本,'mutable'关键字消失了。提问者报告说该版本也起作用。 – user2357112
@ user2357112 - 它并不真正工作,虽然:http://ideone.com/2MVs0O –