65

I'm trying to figure out how/if I can use unique_ptr in a queue.

// create queue
std::queue<std::unique_ptr<int>> q;

// add element
std::unique_ptr<int> p (new int{123});
q.push(std::move(p));

// try to grab the element
auto p2 = foo_queue.front();
q.pop(); 

I do understand why the code above doesn't work. Since the front & pop are 2 separate steps, the element cannot be moved. Is there a way to do this?

1 Answer 1

97

You should say explicitly that you want to move the pointer out of the queue. Like this:

std::unique_ptr<int> p2 = std::move(q.front());
q.pop();
11
  • 3
    @iliacholy: loosely speaking, q.front() returns an l-value, so you cannot copy-initialize p2 with it because unique_ptrs are not copyable. std::move converts it to an r-value, so now p2 is being move-initialized instead, which is allowed by design. Commented Jan 2, 2013 at 21:33
  • 29
    Also important is that after the move, the top element in the queue is a unique_ptr equal to nullptr. The pop is needed to remove this "empty" unique_ptr from the queue.
    – rubenvb
    Commented Jan 3, 2013 at 14:24
  • 1
    why wouldn't pop() just return the top item as an rvalue, I wonder?
    – Mordachai
    Commented Jul 8, 2013 at 20:06
  • 4
    @Mordachai: exception safety requires it.
    – moswald
    Commented Jul 9, 2013 at 2:48
  • 2
    All of which combine to make it a terrible interface for a smarter-pointer based stack or queue. Interesting, but C++ constantly makes pointed-to vs. by-copy require very different semantics to make things work well, IMO.
    – Mordachai
    Commented Jul 11, 2013 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.