1

Moving a const reference to a unique_ptr fails to compile. Problem comes about when I try to do top() on a priority_queue and then pop() the top. I can't get the item before the pop()!

const std::unique_ptr<int>& refToPtr = pqueue.back();
std::unique_ptr<int> ptr = std::move(refToPtr); // fails to compile

Here is a full example.

#include <memory>
#include <queue>
#include <vector>

int main(int argc, char** argv) {
    std::unique_ptr<int> initial = std::make_unique<int>(4);
    std::priority_queue<std::unique_ptr<int>> queue;
    queue.push(std::move(initial));
    const std::unique_ptr<int>& refToPtr = queue.top();
    std::unique_ptr<int> ptr = std::move(refToPtr); // won't compile???
    queue.pop();

    return 0;
}
user2183336
  • 706
  • 8
  • 19
  • No question has been asked, but this is correct behavior. If a `unique_ptr` is const, you can not move it. The purpose of `const` is to prevent change. – Drew Dormann Jul 26 '21 at 20:07
  • Why are you using a reference to `const`? A `const` thing can't be moved as moving involves modifying the object. – NathanOliver Jul 26 '21 at 20:07
  • @NathanOliver Yes, thank you for asking. I tried to state my reason in the question. I have a `priority_queue>`. `std::priority_queue.top()` returns a const reference. I need to get that value before popping. – user2183336 Jul 26 '21 at 20:09
  • Based on the details provided in the comments, this question is a duplicate. – François Andrieux Jul 26 '21 at 20:11
  • Potential duplicate: https://stackoverflow.com/questions/16661038 – Drew Dormann Jul 26 '21 at 20:12
  • The best solution is probably to implement your own priority queue with a mutable `top`, or with a returning `pop`. You can implement this without too much trouble by storing elements in list and using a priority_queue of iterators to elements of that list. – François Andrieux Jul 26 '21 at 20:13

0 Answers0