10

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.

10
  • 13
    Why not var = std::move(vec.back()); vec.pop_back();? Commented Apr 14, 2017 at 17:14
  • 2
    Ok, but what state would vec.back() be in between the two operations? Not valid I'd say, is that correct? Commented Apr 14, 2017 at 17:16
  • 3
    It will be in "moved-from" state. Whether is this state valid, depends on how type is implemented, but all std types are in "valid but unspecified" state, which is generally recomended for user defined types as well. Commented Apr 14, 2017 at 17:19
  • 6
    @boofaz: The move 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. Commented Apr 14, 2017 at 17:19
  • 3
    And any type is supposed to be at least destructible when moved-from, and you don't need anything more from it. Commented Apr 14, 2017 at 17:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is a proposal for this (P3182) with a lot of details about exception safety and so on: open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3182r1.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.