从队列中删除unique_ptr [英] remove unique_ptr from queue
本文介绍了从队列中删除unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想弄清楚如何/如果我可以在队列
中使用 unique_ptr
>
I'm trying to figure out how/if I can use unique_ptr
in a queue
.
// create queue
std::queue<std::unique_ptr<int>> q;
// add element
std::unique_ptr<int> p (new int{123});
q.push(std::move(p));
// try to grab the element
auto p2 = foo_queue.front();
q.pop();
我明白为什么上面的代码不工作。由于前
& pop
是两个单独的步骤,无法移动元素。有没有办法做这个?
I do understand why the code above doesn't work. Since the front
& pop
are 2 separate steps, the element cannot be moved. Is there a way to do this?
推荐答案
你应该明确说明你要移动指针出队列。像这样:
You should say explicitly that you want to move the pointer out of the queue. Like this:
std::unique_ptr<int> p2 = std::move(q.front());
q.pop();
这篇关于从队列中删除unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文