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.
var = std::move(vec.back()); vec.pop_back();
? – Palmaryvec.back()
be in between the two operations? Not valid I'd say, is that correct? – Moonsetmove
is required to leave the object in a state that's valid to at least some degree, so you can still (at least) destroy it, which is all you're doing here. I believe you should be fine as long as you don't try to interleave any other use of the vector's data between the move and the pop_back. – Hiattpop_back()
could return avalue_type&&
. Those who don't want the ex-element can ignore it, but those who do get to write 1 line, instead of 2 or 3. – Undermannedpop()
in general does not return is it can not be implemented efficiently. Implementingtop()
andpop()
allows for an efficient implementation. More detail: cpptruths.blogspot.com/2005/10/… – Bengalivoid
-returningpop()
does. Opting into that via a function with a different name that returns the value would be one solution. But I guess it's too trivial for the Standard to add that, and trivial enough that we can do it ourselves. – UndermannedT
does not support move) which is why this functionality was not added to the standard. The standard wants to make sure we can write generic code that is as efficient as possible (without overcomplicating things) in the most logical way possible. – Bengali