是否允许在 C++ 中自行移动对象?

Is it allowed to self-move an object in C++?

是否允许对象(特别是 std class)自行移动或它是未定义的行为?

考虑一个例子:

#include <iostream>
#include <string>

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

在 gcc/clang 中,程序不打印任何内容,因此 s 字符串在移动过程中丢失: https://gcc.godbolt.org/z/xqTWKfMxM

但在 MSVC 中它工作正常。

来自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