c++c++14movemove-semantics

Is `[](std::list<int>& list){return std::move(list);}(list)` guaranteed to leave `list` empty?


More particularly:

struct A{
    std::list<int> list;
    std::list<int> foo(){
        return std::move(list);
    }
}

A a;
// insert some elements into a.list
a.foo(); // is this guaranteed to clear a.list?

Is the last line above guaranteed to leave a.list empty?


Solution

  • No. Moving from most standard library classes leaves them in a "valid but unspecified state" [1]. That means you have to explicitly clear a.list in order to ensure that it's empty after the move.

    [1] There are exceptions to this rule: most notably, std::unique_ptr is required to be null after a move.