std::string a = "xxx";
std::string b = std::move(a);
//这时候的a,处于什么状态呢
a = "bbbbb";//合法吗?
因为我实际用下来好像有点问题。所以我就想知道,在标准中,是怎么描述这个问题的。
PHPz2017-04-17 14:53:13
C++11 21.4.3.17: basic_string(basic_string&& str, const Allocator& alloc);
str is left in a valid state with an unspecified value.
Because a is actually an lvalue and is converted to an rvalue, so b will point to a's data() buffer. At this time, a is in an undefined state, and it is unsafe to access the value of a again.
But a = "bbbbb"
is legal.
Because this a overloads the assignment operator. basic_string<charT,traits,Allocator>& operator=(const charT* s);
will return a *this = basic_string<charT,traits,Allocator>(s)
which is equivalent to constructing a new temporary object basic_string rvalue. It will copy the value of "bbbbb", which means a points to the newly allocated buffer, so there should be no problem.
黄舟2017-04-17 14:53:13
I don’t think there will be any problem. string
is a string after all. See that the gcc
implementation that comes with string
is implemented using swap
. operator = (&&)
The standard meaning is move
stl
is in an uncertain state after that, which guarantees that move
should also be in a state of 空
after that, but string
does not belong to stl