c++11 - c++标准有关于处在moved状态的容器的说明吗?
黄舟
黄舟 2017-04-17 14:51:13
0
2
569
std::string a = "xxx";
std::string b = std::move(a);
//这时候的a,处于什么状态呢
a = "bbbbb";//合法吗?

因为我实际用下来好像有点问题。所以我就想知道,在标准中,是怎么描述这个问题的。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
PHPzhong

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.

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template