c++ - Getting a unique_ptr out of a priority queue -
i maintaining set of unique_ptr
instances in priority_queue
. @ point, want first element , remove queue. however, produces 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 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 /usr/include/c++/4.8/memory:81:0, uptrtest.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here unique_ptr(const unique_ptr&) = delete; ^
changing code use queue
in this question fixes issue , code compiles fine.
is there no way keep unique_ptr
s in priority_queue
or missing something?
std::priority_queue::top()
returns const reference can't move it. looking @ public interface of priority_queue
there no method non-const reference can move (which mandatory unique_ptr
, has no copy constructor).
solution: replace unique_ptr
shared_ptr
able copy them (and not move them).
or, of course, use kind of container altogether (but if chose priority_queue
in first place, not acceptable you).
you maybe use "protected member hack" access protected member c
(the underlying container) wouldn't recommend it, quite dirty , quite ub.
Comments
Post a Comment