看看这段代码:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
using namespace std;
int main()
{
ifstream text("text.txt");
istreambuf_iterator<char> iis(text);
string longest_phrase, _longest;
while (iis != istreambuf_iterator<char>()) {
if ( *iis != '.' ) {
_longest.push_back(*iis);
++iis;
continue;
}
if ( _longest.size() > longest_phrase.size() )
longest_phrase = move(_longest); //I want to move the data of _longest to longest_phrase. Just move! Not to copy!
cout << _longest.empty(); //why _longest is not empty??
//_longest.clear();
++iis;
}
text.close();
longest_phrase.push_back('.');
cout << "longest phrase is " << longest_phrase;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码搜索文件中最长的短语.那么为什么从左值到右值的转换不起作用呢?
编辑:这就是为什么我认为它不起作用:
class Vector {
public:
Vector(vector<int> &&v): vec( move(v) ) {}
vector<int> vec;
};
int main()
{
vector<int> ints(50, 44);
Vector obj( move(ints) );
cout << ints.empty();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家的快速和有用的答案!
您不应对标准库的移动对象的状态做出具体假设,除非它是合法状态(除非指定了移动赋值运算符或移动构造函数的其他后置条件).
根据C++ 11标准的第17.6.5.15段:
可以从(12.8)移动C++标准库中定义的类型的对象.可以显式指定或隐式生成移动操作.除非另有规定,否则此类移动物体应置于有效但未指定的状态.
此外,关于basic_string类模板的移动赋值运算符的第21.4.2/21-23段没有说明移动的字符串是否应保留在一个状态,以便调用empty()它返回true.
empty()在这种情况下,调用是合法的,因为它对string调用它的对象的状态没有任何先决条件; 另一方面,您不能对其返回值应该做出假设.