Ilia Choly
Ilia Choly

Reputation: 18557

remove unique_ptr from queue

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?

Upvotes: 64

Views: 22831

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72469

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();

Upvotes: 96

Related Questions