Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL container - pop with move

Is there a STL container (no Boost) from which an element can removed and moved to an lvalue?

Say I have a std::vector of large objects and a variable to which I want to pop an element from the vector.

var = vec.back();  // non-move assign op
vec.pop_back();    // dtor

var = containerWithMovePop.pop_and_return();  // move assign-op

It's not like performance is so important, I just want to know if it's possible.

like image 535
boofaz Avatar asked Apr 14 '17 17:04

boofaz


1 Answers

As @aeschpler says, this works

auto var = std::move(vec.back()); 
vec.pop_back();

vec.back() will be empty (if string) or same (if int), or whatever (depends on the type) between back and pop_back, but that's fine. As the destructor runs in pop_back() there will be very little to do there.

We might get pop_back() to return T in the future now that we have move semantics (as ppl noted, we didn't when std::vector<> was specced), but likely it'd be a new method so to not destroy backward compatibility.

like image 135
Macke Avatar answered Oct 03 '22 17:10

Macke