[英]‘std::ostream’ has no member named ‘close’
std::ostream沒有成員函數close()
。 我不應該關閉什么類型的流?
例如,也許我想關閉std::cout
以防止進一步寫入。
std::cout.close(); // ‘std::ostream’ has no member named ‘close’
如果我使用的是 C 庫,我可以使用以下命令關閉stdout
:
fclose(stdout); // no problem
那么從std::ostream
close()
成員背后的想法是什么?
有關的:
將close()
函數作為std::ostream
的成員是沒有意義的。 第一個例子是std::ostringstream
繼承自std::ostream
。 關閉字符串有意義嗎? std::ostream
的唯一成員是用於輸入/輸出的全局對象。
文件流有一個close()
函數,因為能夠將資源釋放到環境中很重要。 但是,由於從該基類繼承的其他類不需要此函數,因此將其作為std::ostream
的一部分是沒有意義的,這就是它僅用於文件流的原因。
這是一種偽造它的方法:
void ostream_fake_close( std::ostream & os )
{
os.flush();
static std::stringstream closed_flag;
cerr<<(os.rdbuf()==closed_flag.rdbuf()?"closed":"open")<<"\n";
os.rdbuf(closed_flag.rdbuf());
cerr<<(os.rdbuf()==closed_flag.rdbuf()?"closed":"open")<<"\n";
}
未來對流的寫入將被重定向到closed_flag
緩沖區。 您可以通過定期重置緩沖區來限制緩沖區的大小:
closed_flag.str("");
當對象被破壞時,將自動發出真正的關閉。
除了 Meneldal 的出色回答。
如果您稍后需要訪問某些類型的資源,不釋放資源仍然可能會導致問題。 如果由於某種原因您不想使用ofstream
(它有一個close
方法),請堅持使用ostream
。 你可以讓它超出范圍。
例子:
std::string FilePath = "C:/Test/MyFile.ext";
{ // <== Note the start of scope.
// Writing a file using ostream as by example given by cplusplus.com reference.
std::filebuf outfb;
outfb.open(FilePath, std::ios::out);
std::ostream os(&outfb);
/* Do your stuf using 'os' here. */
} // <== Note the end of scope.
/* Here, the resource is freed as if you would have called close. */
/* Rest of code... */
更新:但是,現在我想一想,在這種情況下std::filebuf
提供了close
方法,它也可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.