从优先级队列中获取unique_ptr [英] Getting a unique_ptr out of a priority queue
问题描述
我在 priority_queue
中维护一组 unique_ptr
实例。在某些时候,我想获得第一个元素,并将其从队列中删除。但是,这总是会产生编译器错误。请参阅下面的示例代码。
I am maintaining a set of unique_ptr
instances in a priority_queue
. At some point, I want to get the first element and remove it from the queue. However, this always produces a compiler error. See sample code below.
int main ()
{
std::priority_queue<std::unique_ptr<int>> queue;
queue.push(std::unique_ptr<int>(new int(42)));
std::unique_ptr<int> myInt = std::move(queue.top());
return 1;
}
这会产生以下编译器错误(gcc 4.8.0):
This produces the following compiler error (gcc 4.8.0):
uptrtest.cpp: In function ‘int main()’: uptrtest.cpp:6:53: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’ std::unique_ptr<int> myInt = std::move(queue.top());
^ In file included from /usr/include/c++/4.8/memory:81:0,
from uptrtest.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here
unique_ptr(const unique_ptr&) = delete;
^
更改代码以使用队列
like 此问题修复了问题
Changing the code to use queue
like in this question fixes the issue and the code compiles just fine.
是否无法在 unique_ptr
> priority_queue 还是我缺少某些内容?
Is there no way to keep unique_ptr
s in a priority_queue
or am I missing something?
推荐答案
std :: priority_queue :: top()
返回一个const引用,所以你不能移动它。查看 priority_queue
的公开界面,有没有方法来获取一个非const引用你可以移动(这是 unique_ptr
的强制性,它没有复制构造函数)。
std::priority_queue::top()
returns a const reference so you can't move it. Looking at the public interface of priority_queue
there is no method to get a non-const reference that you can move (which is mandatory for unique_ptr
, it has no copy constructor).
解决方案:使用 shared_ptr
替换 unique_ptr
(而不只是移动它们)。
Solution: replace unique_ptr
with shared_ptr
to be able to copy them (and not just move them).
或者,当然,使用另一种类型的容器(但如果你选择 priority_queue $ c
Or, of course, use another kind of container altogether (but if you chose priority_queue
in the first place, this is probably not acceptable for you).
您也可以使用受保护的成员黑客来访问受保护的成员 c
(底层容器),但我不会推荐它,这是相当肮脏,很可能UB。
You could also maybe use a "protected member hack" to access the protected member c
(the underlying container) but I wouldn't recommend it, this is quite dirty and quite probably UB.
这篇关于从优先级队列中获取unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!