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?
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.
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.
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.
yes, it's an RAII class.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With