Search code examples
c++move

Are move semantics guaranteed by the standard?


I think I understand the gist of move-semantics in general but am wondering, whether the C++ standard actually guarantees move-semantics for std-types like std::vector. For instance is the following snippet guaranteed to produce check = true (if the used compiler/std-lib is standard-compliant)?

std::vector<int> myVec;
int *myPtr = myVec.data();
std::vector<int> otherVec = std::move(myVec);
int *otherPtr = otherVec.data();

bool check = myPtr == otherPtr;

In other words: When moving a a std::vector, does the standard guarantee that I will actually perform a move and not a copy after all (e.g. because the used std-lib hasn't implemented a move-constructor for std::vector)?


Solution

  • I believe this is guaranteed for allocator-aware containers by the following requirement from [tab.container.alloc.req]:

    X(rv) X u(rv); Postconditions: u has the same elements as rv had before this construction;...

    Note the words "same elements", not "elements with the same content". For instance, after

    std::vector<int> otherVec = std::move(myVec);
    

    first element of otherVec must therefore be the very same element/object that was the first element of myVec before this move-construction.