是否移动分配 std::fstream 关闭原始流
Does move assign an std::fstream close the original stream
从 c++11 开始,我们可以将一个 std::fstream
对象分配给另一个对象,但我找不到说明如果 fstream
对象已经与一个文件 (is_open()==true
).
所以我的问题是在下面的代码中,File1.txt
是否会正确关闭,或者我是否必须手动关闭它。如果我必须手动完成,如果我不这样做会怎样?
std::fstream file("File1.txt");
file = std::fstream("File2.txt"); //will this implicitly call file.close()?
由于实际的文件相关机制 'hidden' 在相应的缓冲区内(流实际上主要提供格式化 IO),您应该查看 std::basic_filebuf
文档:
First calls close() to close the associated file, then moves the
contents of rhs into *this: the put and get buffers, the associated
file, the locale, the openmode, the is_open flag, and any other state.
After the move, rhs is not associated with a file and rhs.is_open() ==
false.
复制自http://en.cppreference.com/w/cpp/io/basic_filebuf/operator%3D
fstream
对象的移动分配将导致其关联的 filebuf
的移动分配。该文档非常清楚地表明旧文件首先关闭(好像 file.rdbuf()->close()
而不是 file.close()
):
basic_filebuf& operator=(basic_filebuf&& rhs);
- 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
.
- Returns:
*this
.
basic_fstream& operator=(basic_fstream&& rhs);
- Effects: Move assigns the base and members of
*this
from the base and corresponding members of rhs
.
- Returns:
*this
.
(这是草案 n4527 中的措辞,至少自 n3485 以来未更改)
从 c++11 开始,我们可以将一个 std::fstream
对象分配给另一个对象,但我找不到说明如果 fstream
对象已经与一个文件 (is_open()==true
).
所以我的问题是在下面的代码中,File1.txt
是否会正确关闭,或者我是否必须手动关闭它。如果我必须手动完成,如果我不这样做会怎样?
std::fstream file("File1.txt");
file = std::fstream("File2.txt"); //will this implicitly call file.close()?
由于实际的文件相关机制 'hidden' 在相应的缓冲区内(流实际上主要提供格式化 IO),您应该查看 std::basic_filebuf
文档:
First calls close() to close the associated file, then moves the contents of rhs into *this: the put and get buffers, the associated file, the locale, the openmode, the is_open flag, and any other state. After the move, rhs is not associated with a file and rhs.is_open() == false.
复制自http://en.cppreference.com/w/cpp/io/basic_filebuf/operator%3D
fstream
对象的移动分配将导致其关联的 filebuf
的移动分配。该文档非常清楚地表明旧文件首先关闭(好像 file.rdbuf()->close()
而不是 file.close()
):
basic_filebuf& operator=(basic_filebuf&& rhs);
- Effects: Calls
this->close()
then move assigns fromrhs
. After the move assignment*this
has the observable state it would have had if it had been move constructed fromrhs
.- Returns:
*this
.
basic_fstream& operator=(basic_fstream&& rhs);
- Effects: Move assigns the base and members of
*this
from the base and corresponding members ofrhs
.- Returns:
*this
.
(这是草案 n4527 中的措辞,至少自 n3485 以来未更改)