'How to retrieve the element of the container with unique_ptr in c++?
I used vector like this:
int main(void) {
std::vector<int> queue;
queue.push_back(5);
queue.push_back(4);
if (!queue.empty()) {
int data = queue.back();
if (something_happens) {
queue.pop_back();
}
}
}
However, If I use vectors with unique_ptr:
std::vector<unique_ptr<int>> queue;
how to use back()?
Should I pass the ownership to the element of unique_ptr to the caller of back() even if the pop() does not occur?
If I have to pass the ownership, how the container again takes the ownership?
Solution 1:[1]
how to use
back()?
It depends. If you don't want to transfer the ownership of queue.back(), then you can use reference to accept it
auto&& data = queue.back();
Or you can use std::move to transfer its ownership to the temporary variable
auto data = std::move(queue.back());
If I have to pass the ownership, how the container again takes the ownership?
Similarly, just use std::move to transfer the ownership of data back to queue.back()
queue.back() = std::move(data);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
