Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Ilia Choly Avatar asked Jan 02 '13 18:01

Ilia Choly


People also ask

Can unique_ptr be moved?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

Does unique_ptr delete itself?

unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.

Is unique_ptr an example of Raii idiom?

yes, it's an RAII class.


1 Answers

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(); 
like image 154
Yakov Galka Avatar answered Sep 30 '22 07:09

Yakov Galka