从原始指针创建唯一指针,以确保超出范围时将其删除

时间:2019-03-19 13:40:19

标签: c++ c++11

我们在代码中使用了Boost循环队列(特别是boost::circular_buffer<std::unique_ptr<Interface>>)。我要编写代码,从队列中获取特定类型的数据,否则从队列中删除。

void chkdata()
{
.....
 // auto data = get the first element from the circular buffer
// need to implement like this so that auto delete will happen
}

我该如何实现?

1 个答案:

答案 0 :(得分:0)

For rawpacket to destroy the message when it leaves scope, you just need

auto rawpacket = std::move(buf.front());

It also sounds like you should remove the (now null) moved-from pointer from the queue

buf.pop_front();

You are being confused by the implicit conversion occuring at the insertion side, where a std::unique_ptr<IMsg> is constructed from a Obj* in the call buf.insert(data);. Presumably Obj inherits from IMsg.