gpt4 book ai didi

c++ - ofstream - 需要在 close() 操作后删除对象句柄吗?

转载 作者:太空狗 更新时间:2023-10-29 20:06:05 24 4
gpt4 key购买 nike

我有一个简单的问题。我有一个要写入数据的 ofstream。完成并调用 close() 后,我需要在句柄上调用 delete 还是 close() 执行清理?

例如:

mFileStream = new std::ofstream(LogPath.c_str(), std::ios::trunc);
...
mFileStream->Close();
//delete mFileStream?

我的直觉是肯定的,因为我已经分配了它,但我不确定我在哪里读到它。谁能解释一下?

最佳答案

是的,你必须这样做。在 C++ 中,您必须将 newdelete 配对。

虽然,在像这样的简单情况下您不需要,您可以在堆栈上分配您的对象,它会为您销毁,强烈建议这样做(更快更安全):

{ // enclosing scope (function, or control block)
ofstream mFileStream(LogPath.c_str(), std::ios::trunc);
...
mFileStream.close(); // mFileStream is not a pointer any more, use the "." operator
// mFileStream destroyed for you here. "close" may even be called for you.
}

小提示:close带有一个小“c”。

关于c++ - ofstream - 需要在 close() 操作后删除对象句柄吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541897/

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