我有一个简单的问题。我有一个要写入数据的 ofstream。完成并调用 close()
后,我需要在句柄上调用 delete
还是 close()
执行清理?
例如:
mFileStream = new std::ofstream(LogPath.c_str(), std::ios::trunc);
...
mFileStream->Close();
//delete mFileStream?
我的直觉是肯定的,因为我已经分配了它,但我不确定我在哪里读到它。谁能解释一下?
最佳答案
是的,你必须这样做。在 C++ 中,您必须将 new
和 delete
配对。
虽然,在像这样的简单情况下您不需要,您可以在堆栈上分配您的对象,它会为您销毁,强烈建议这样做(更快更安全):
{ // 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/