c++ 如何访问原子非 POD 成员变量

c++ How do I access atomic non-POD member variables?

本文关键字:POD 成员 变量 何访问 访问 c++      更新时间:2023-10-16

我有一个类

class connection
{
private:
  static std::atomic<std::shared_ptr<std::queue<buffer<char> > > > queue_;
  std::thread serviceThread_;
  std::shared_ptr<std::condition_variable> notEmpty_;
  int fileDesc_;
public:
  connection(std::shared_ptr<std::condition_variable> notEmpty,
             int fileDesc):
    serviceThread_(), notEmpty_(notEmpty), fileDesc_(fileDesc)
  {
    serviceThread_ = std::thread(&connection::service, this);
  }
  void service();
  void join(){ serviceThread_.join(); }
};

connection::service(),我打电话给queue_.pop()queue_->pop(),试图获得我认为应该是队列顶部的东西。

当我打电话给queue_.pop()时,我收到错误:

server/connection.hpp: In member function ‘void connection::service()’:
server/connection.hpp:78:29: error: ‘struct         
std::atomic<std::shared_ptr<std::queue<buffer<char> > > >’ has no member named 
‘pop’ 
queue_.pop();"

很公平,因为它是一个原子共享指针。如果我调用queue_->pop(),则会收到以下错误:

server/connection.hpp: In member function ‘void connection::service()’:
server/connection.hpp:78:28: error: base operand of ‘->’ has non-pointer type    
‘std::atomic<std::shared_ptr<std::queue<buffer<char> > > >’
queue_->pop();"

我有两个问题。

  1. 如何调用原子共享指针中的队列成员函数?

  2. 是否有一些调试内容显示对象的成员变量?让我更好地了解我实际上想玩什么。

static std::atomic<std::shared_ptr<std::queue<buffer<char> > > > queue_;

这里的大红旗。 std::atomic是一把魔锁。当您访问shared_ptr时,它只是一个普通shared_ptr,就像任何其他一样。

如果需要锁,请使用 std::mutexstd::lock_guard 。如果你不这样做,那就什么都不做。无论如何,std::shared_ptr都不应该装饰。

此外,容器的全局shared_ptr本身是奇怪的。所有这些都表明queue必须显式初始化并且可能被销毁,因此您已经创建了空队列和不存在队列之间的区别。这看起来像是不必要的复杂性和开销,而不是简单的全局队列。