This (s=std::move(s)
)came up in a recent question I asked. The consensus was that self assignment from an rvalue to an lvalue should be checked and prevented much like a regular self assignment s=s
. To me this seems like unnecessary additional code as I can't imagine where an rvalue self assignment would occur. But I tested this code with GCC, CLANG, and MSVC to see what the default move assignment did.
#include <iostream>
#include <string>
#include <utility>
int main()
{
std::string s{"asdfasdfasdfasdf"};
s=std::move(s);
std::cout << "String is: " << s << '\n';
}
GCC and CLANG changed s to a null string. MSVC didn't modify s. Which is correct or is this UB?
Note: thanks to the person(s) that identified a duplicate, it's clear the answer is that GCC, CLANG, and MSVC are all correct. Different results are permitted and it's not UB! Wow. Go read the links.
GCC and CLANG output self assignment warnings like this.
warning: moving 's' of type 'std::string' {aka 'std::__cxx11::basic_string'} to itself [-Wself-move]