c++ 如何访问原子非 POD 成员变量
c++ How do I access atomic non-POD member variables?
我有一个类
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();"
我有两个问题。
如何调用原子共享指针中的队列成员函数?
是否有一些调试内容显示对象的成员变量?让我更好地了解我实际上想玩什么。
static std::atomic<std::shared_ptr<std::queue<buffer<char> > > > queue_;
这里的大红旗。 std::atomic
是一把魔锁。当您访问shared_ptr
时,它只是一个普通shared_ptr
,就像任何其他一样。
如果需要锁,请使用 std::mutex
和 std::lock_guard
。如果你不这样做,那就什么都不做。无论如何,std::shared_ptr
都不应该装饰。
此外,容器的全局shared_ptr
本身是奇怪的。所有这些都表明queue
必须显式初始化并且可能被销毁,因此您已经创建了空队列和不存在队列之间的区别。这看起来像是不必要的复杂性和开销,而不是简单的全局队列。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 根据 MSVC,具有易失性成员的结构不再是 POD
- POD 结构(相同类型的成员):成员是否位于连续的内存位置?
- 类POD成员变量初始化
- 检测Sfinae POD类型的第一成员
- POD成员默认初始化无括号
- 视觉C++似乎正在零初始化一个不应该的类的 POD 成员
- 在C中使用具有虚拟成员(即非POD)的C++结构
- 向包含POD和非POD成员的现有结构添加移动语义
- 类 POD 成员默认初始化与零初始化与无初始化
- 对空的用户定义构造函数将如何初始化非静态非 POD 成员变量感到困惑
- 循环POD成员
- c++ 11 VS2013类POD成员初始化
- 迭代器默认构造函数和POD成员初始化
- c++ 如何访问原子非 POD 成员变量
- 使c++对未初始化的POD成员变量发出警告
- 如何在联合中初始化非 POD 成员
- 放置新的和未初始化的POD成员