2

Is it permitted for an object (in particular of an std class) to be self-moved or it is an undefined-behavior?

Consider an example:

#include <iostream>
#include <string>

int main()
{
    std::string s("123");
    s = std::move(s);
    std::cout << s;
}

In gcc/clang the program prints nothing, so s string is lost during moving: https://gcc.godbolt.org/z/xqTWKfMxM

But in MSVC it works fine.

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 1
    For most standard C++ objects, a **move** on an object leaves it in a valid-but-unspecified state, suitable to be destructed or re-assigned to (also any member functions without pre-requisites are okay, and some objects have additional guarantees, like unique_ptr and vector). In the case you have here, you are accessing the valid-but-unspecified state `s` object, which will lead to all sorts of problems. – Eljay Jul 06 '21 at 17:32

1 Answers1

4

From cpp ref:

Also, the standard library functions called with xvalue arguments may assume the argument is the only reference to the object; if it was constructed from an lvalue with std::move, no aliasing checks are made. However, self-move-assignment of standard library types is guaranteed to place the object in a valid (but usually unspecified) state:

std::vector<int> v = {2, 3, 3};
v = std::move(v); // the value of v is unspecified
Afshin
  • 8,839
  • 1
  • 18
  • 53