我有一个简单的问题。我有一个写入数据的流。完成并调用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.
}
小提示:这是带有小“c”的
close
。