为什么
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 临时变量应该跟 file_没有关系才对吧
为什么
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 临时变量应该跟 file_没有关系才对吧
|
1
```
std::string i = "asdga"; std::string j = "asgwqet"; std::string k = std::move(std::string(j.begin(), j.end())); ``` 这个执行之后 j 还是 j ,不为空 |
|
mrwhyzzzNov 15, 2024
2
@yippee0539 因为你 move 的是一个新的 string ,std::string(j.begin(), j.end()),相当于新建了一个 string ,拷贝的 j 的内容
|
|
mainjzbNov 15, 2024
3
因为 move 不应该叫 move
move 底层就是个类型强转,把对象标记为右值。 std::move 本身不改变对象的状态。 实际的状态变化由类型的移动构造函数或移动赋值操作符决定。 万一你输入的是 std::move(std::string(j.begin(), j.end() -1 )); // 大概不这么写 少一个字母。又该如何呢。 所以显然用 iterate 的情况下移动构造函数仅进行了复制。 |
|
4
额,file 不是 null ,是直接到 EOF 了
|
|
5
@mainjzb 涨知识了
|
|
leonshawNov 15, 2024
6
file_ 一个对象怎么会是 null
|
|
nlzyNov 15, 2024
7
这个和 move 没有任何关系,std::move(std::string(...)) 中的 std::string(...) 本身就已经是可移动的右值了。在这个场景下有没有 std::move 都是一样的
file_ 变 eof 是因为 istreambuf_iterator 把文件流的内容读完了,读完之后就是 eof 。 |
|
8
@nlzy #7 和 move 没关系,EOF 的部分也对,但是 move 是有(不好的)效果的。
如果写 string s = string(…, …); 那么 C++17 下等价于 string s{…, …}; 不存在“临时变量构造完再移动”的过程。 如果写 string s = move(string(…, …)); 那么现行标准下含义是先构造临时变量再移动,且是不可省略移动的情况。 |