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;
}
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;
^
Changing the code to use queue
like in this question fixes the issue and the code compiles just fine.
Is there no way to keep unique_ptr
s in a priority_queue
or am I missing something?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…