2012-03-02 27 views
1

我有一个简单的问题。我有一个我写数据的ofstream。完成后请致电close(),我是否需要拨打电话delete或拨打close()进行清理?ofstream - 需要在close()操作后删除对象句柄?

例如:

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

我的直觉是肯定的,因为我已经分配了,但我不知道在那里我阅读。任何人都可以澄清?

+2

在这种情况下,您需要调用'delete'。该对象分配在堆上,'close()'只关闭所有对绑定到这个对象的实际文件的引用。它不以任何方式处理实际对象的清理。 – 2012-03-02 23:41:31

回答

8

是的,你必须。在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”。

0

所有分配有new的对象都必须具有相应的delete以避免泄漏。 new[]delete[](这些碰巧是单独的运营商,BTW)也是如此。

作为J.N.在上面的代码示例中指出,不妨使用堆栈并避免操作符new/delete。如果流的使用仅限于某个明确定义的范围,则不需要在免费商店(堆)上创建对象。

你实际上不需要的是拨打close。文件流在被销毁时已经关闭(在destuctor中),所以可以忽略它。事实上,这是使用文件流对象上的fopen/FCLOSE我们可以看到这里的一大优势:Do I need to manually close an ifstream?

此外,如果您使用C++斯特劳斯具有较强的一致性鼓励他RAII成语的方式,一般希望避免编写需要手动调用删除的代码。这可能是有点在你的头上的那一刻,但我们必须在C++ 11像shared_ptrunique_ptr可用的智能指针,它会自动销毁对象为我们:如果你冒险进入C的境界

shared_ptr<ofstream> output_stream(new ofstream(...)); 
// ^^ This will not leak and the file will gracefully close 
// when 'output_stream' is destroyed. It makes the need to 
// call both delete and close unnecessary. 

++异常处理,你会发现这种使用析构函数自动清理资源不仅方便,而且对于安全正确地进行编码而言非常重要。