2012-03-02 93 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. 

++異常處理,你會發現這種使用析構函數自動清理資源不僅方便,而且對於安全正確地進行編碼而言非常重要。