为什么
std::fstream file_("path_to_file"); std::string content_ = std::move(std::string(std::istreambuf_iterator<char>(file_), std::istreambuf_iterator<char>()));
执行之后 file_为 null 了
这里构造的 string 临时变量应该跟 fie_没有关系才对吧
1 yippee0539 OP ``` std::string i = "asdga"; std::string j = "asgwqet"; std::string k = std::move(std::string(j.begin(), j.end())); ``` 这个执行之后 j 还是 j ,不为空 |
2 mrwhyzzz 329 天前 @yippee0539 因为你 move 的是一个新的 string ,std::string(j.begin(), j.end()),相当于新建了一个 string ,拷贝的 j 的内容 |
![]() | 3 mainjzb 329 天前 因为 move 不应该叫 move move 底层就是个类型强转,把对象标记为右值。 std::move 本身不改变对象的状态。 实际的状态变化由类型的移动构造函数或移动赋值操作符决定。 万一你输入的是 std::move(std::string(j.begin(), j.end() -1 )); // 大概不这么写 少一个字母。又该如何呢。 所以显然用 iterate 的情况下移动构造函数仅进行了复制。 |
4 yippee0539 OP 额,file 不是 null ,是直接到 EOF 了 |
5 yippee0539 OP @mainjzb 涨知识了 |
6 leonshaw 329 天前 file_ 一个对象怎么会是 null |
![]() | 7 nlzy 329 天前 这个和 move 没有任何关系,std::move(std::string(...)) 中的 std::string(...) 本身就已经是可移动的右了。在这个场景下有没有 std::move 都是一样的 file_ 变 eof 是因为 istreambuf_iterator 把文件流的内容读完了,读完之后就是 eof 。 |