c – Mutex的锁定/解锁功能是否为“const”?

前端之家收集整理的这篇文章主要介绍了c – Mutex的锁定/解锁功能是否为“const”?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在维护一个包含Mutex类的库.我不能决定这个类暴露的lock()和unlock()函数是否应该是const.我在网上寻找类似的代码,可以找到这两个实现.

首先实现,lock()和unlock()不是const.这意味着在const函数中使用Mutex类的人应该额外调用Mutex的函数

  1. class Mutex
  2. {
  3. public:
  4. void lock();
  5. void unlock();
  6. };
  7.  
  8. class Foo
  9. {
  10. public:
  11. void getBar(Bar& bar) const
  12. {
  13. m_mutex.lock();
  14. bar = m_bar;
  15. m_mutex.unlock();
  16. }
  17.  
  18. private:
  19. // Mutable,responsability of the user (or we could use a const_cast when needed)
  20. mutable Mutex m_mutex;
  21. Bar m_bar;
  22. };

第二个实现,即使这个声音听起来不是很自然(因为我们修改了Mutex的实例),但是在他的一个const函数调用这些函数的时候,用户就不用烦恼了,

  1. class Mutex
  2. {
  3. public:
  4. void lock() const;
  5. void unlock() const;
  6. };
  7.  
  8. class Foo
  9. {
  10. public:
  11. void getBar(Bar& bar) const
  12. {
  13. m_mutex.lock();
  14. bar = m_bar;
  15. m_mutex.unlock();
  16. }
  17.  
  18. private:
  19. Mutex m_mutex;
  20. Bar m_bar;
  21. };

你喜欢什么解决方案?我希望你的意见能够帮助我做出决定.

解决方法

这种东西是可变的.也就是说,mutable适用于不参与对象的逻辑常量的事物. (如果一个值为“逻辑常数”,则表示“主”值为常数,对象的值从外部不能更改.)

您的对象的值独立于互斥体的状态(它只是提供一致性的实现细节,它的状态在类之外是不知道的),这是您的互斥体应该是可变的.

注意,你不应该去const_cast路由. This leads to undefined behavior如果你这样做的:

  1. const Foo f;
  2.  
  3. Bar b;
  4. f.getBar(b); // takes const off of mutex,modifies (bang you're dead)

猜你在找的C&C++相关文章