gpt4 book ai didi

c++ - 是否 move 分配一个 std::fstream 关​​闭原始流

转载 作者:可可西里 更新时间:2023-11-01 15:56:39 27 4
gpt4 key购买 nike

从 c++11 开始,我们可以 move 分配一个 std::fstream反对另一个,但我找不到说明如果 fstream 会发生什么的文档对象已与文件 ( is_open()==true) 相关联。

所以我的问题是是否在下面的代码中,File1.txt将正确关闭或者如果我必须手动关闭它。如果我必须手动完成,如果我不这样做会怎样?

std::fstream file("File1.txt");   
file = std::fstream("File2.txt"); //will this implicitly call file.close()?

最佳答案

fstream 对象的 move 赋值将导致其关联的filebuf 的 move 赋值。该文档非常清楚地表明旧文件首先关闭(就像 file.rdbuf()->close() 而不是 file.close()) :

basic_filebuf& operator=(basic_filebuf&& rhs);

  1. Effects: Calls this->close() then move assigns from rhs. After the move assignment *this has the observable state it would have had if it had been move constructed from rhs.
  2. Returns: *this.

basic_fstream& operator=(basic_fstream&& rhs);

  1. Effects: Move assigns the base and members of *this from the base and corresponding members of rhs.
  2. Returns: *this.

(这是草案 n4527 中的措辞,至少自 n3485 以来没有变化)

关于c++ - 是否 move 分配一个 std::fstream 关​​闭原始流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com