remove unique_ptr from queue

C++C++11Unique Ptr

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIlia CholyView Question on Stackoverflow
Solution 1 - C++Yakov GalkaView Answer on Stackoverflow