Reputation: 941
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?
Upvotes: 0
Views: 64
Reputation: 42756
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);
Upvotes: 1