看下面的代码:
#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;
}
此代码搜索文件中最长的短语。
那么,为什么从左值到右值的转换不起作用?
编辑:
这就是为什么我认为它不起作用的原因:
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;
}
谢谢大家的快速有用的回答!
最佳答案
除了标准库的移出对象的状态为合法状态外,您不应做出具体假设(除非指定了移动赋值运算符或move构造函数的其他后置条件)。
根据C++ 11标准第17.6.5.15段:
此外,关于basic_string
类模板的move-assignment运算符的第21.4.2 / 21-23段没有指定关于应将移自字符串的状态保持为在其上调用empty()
返回true
的状态。
在这种情况下,调用empty()
是合法的,因为它对调用它的string
对象的状态没有任何先决条件。另一方面,您无法假设其返回值是多少。