That seems to be an oversight in the design of std::priority_queue<T>
. There doesn't appear to be a way to directly move (not copy) an element out of it. The problem is that top()
returns a const T&
, so that cannot bind to a T&&
. And pop()
returns void
, so you can't get it out of that either.
However, there's a workaround. It's as good as guaranteed that the objects inside the priority queue are not actually const
. They are normal objects, the queue just doesn't give mutable access to them. Therefore, it's perfectly legal to do this:
MyClass moved = std::move(const_cast<MyClass&>(l.top()));
l.pop();
As @DyP pointed out in comments, you should make certain that the moved-from object is still viable for being passed to the queue's comparator. And I believe that in order to preserve the preconditions of the queue, it would have to compare the same as it did before (which is next to impossible to achieve).
Therefore, you should encapsulate the cast & top()
and pop()
calls in a function and make sure no modifications to the queue happen in between. If you do that, you can be reasonably certain the comparator will not be invoked on the moved-from object.
And of course, such a function should be extremely well documented.
Note that whenever you provide a custom copy/move constructor for a class, you should provide the corresponding copy/move assignment operator as well (otherwise, the class can behave inconsistently). So just give your class a deleted copy assignment operator and an appropriate move assignment operator.
(Note: Yes, there are situations when you want a move-constructible, but not move-assignable class, but they're extremely rare (and you'll know them if you ever find them). As a rule of thumb, always provide the ctor and assignment op at the same time)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…