Ili*_*oly 51 c++ unique-ptr c++11
我试图找出如何/我是否可以使用unique_ptr在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();
Run Code Online (Sandbox Code Playgroud)
我明白为什么上面的代码不起作用.由于front&pop是2个单独的步骤,因此无法移动元素.有没有办法做到这一点?
ybu*_*ill 70
你应该明确地说,你要移动鼠标指针从队列中.像这样:
std::unique_ptr<int> p2 = std::move(q.front());
q.pop();
Run Code Online (Sandbox Code Playgroud)