2012-07-26 42 views
2

我知道一個析構函數本質上是一個釋放內存的函數,或者每當你完成它的時候就進行一次「清理」。什麼應該在一個合適的析構函數中?

我的問題是,什麼在一個適當的析構函數?

讓我告訴你一類我有一些代碼:

#ifndef TRUCK_H__ 
#define TRUCK_H__ 

#include <iostream> 
#include "printer.h" 
#include "nameserver.h" 
#include "bottlingplant.h" 

using namespace std; 

class BottlingPlant; // forward declaration 

class Truck { 

    public: 
    Truck(Printer &prt, 
      NameServer &nameServer, 
      BottlingPlant &plant, 
      unsigned int numVendingMachines, 
      unsigned int maxStockPerFlavour); 
    ~Truck(); 
    void action(); 

    private: 
    Printer* printer;  // stores printer 
    NameServer* ns;   // stores nameserver 
    BottlingPlant* bottlingPlant; // stores bottlingplant 
    unsigned int numVM;  // stores number of vendingmachine 
    unsigned int maxStock;  // stores maxStock 
    unsigned int cargo[4];  // stores the cargo. 

}; 

這裏的構造函數:

Truck::Truck(Printer &prt, 
       NameServer &nameServer, 
       BottlingPlant &plant, 
       unsigned int numVendingMachines, 
       unsigned int maxStockPerFlavour) { 
    printer = &prt; 
    printer->print(Printer::Truck, 'S'); 
    ns = &nameServer; 
    bottlingPlant = &plant; 
    numVM = numVendingMachines; 
    maxStock = maxStockPerFlavour; 
    cargo[ 0 ] = 0; 
    cargo[ 1 ] = 0; 
    cargo[ 2 ] = 0; 
    cargo[ 3 ] = 0; 
}//constructor 

在我的析構函數類,我應該指針後清理?也就是, 將它們設置爲NULL?或刪除它們?

Truck::~Truck() 
{ 
    printer = NULL; // or should this be delete printer? 
    ns = NULL; 
    bottlingPlant = NULL; 
    // anything else? or is it fine to leave the pointers the way they are? 
}//destructor 

感謝您的幫助,只是想在創造適當的析構函數的好習慣。

+2

這取決於你的構造函數中有什麼。請參閱:[三條法則是什麼?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree) – Mysticial 2012-07-26 01:17:21

+0

謝謝您的參考。我一定會看看。我已經添加了構造函數供您查看。 – 2012-07-26 01:19:40

+0

看完奈德的回答後,我想你明白了,但我想說的是你可能想在使用前檢查你的指針,因爲有可能是'打印機'的主人刪除它,'卡車'不知道,並且那會導致崩潰。 – shengy 2012-07-26 01:38:46

回答

6

將指針存儲在對象中時,您需要清楚地瞭解誰擁有指向的內存。如果你的類是所有者,那麼析構函數必須釋放內存,否則你會泄漏。如果你的班級不是所有者,那麼你不能釋放內存。

將點設置爲NULL是不必要的,重要的是要正確處理內存本身。

管理指針的一種更簡單的方法是使用智能指針類,它將自動爲您處理。

+1

一致地使用智能指針和其他形式的RAII,您永遠不必編寫自己的析構函數 - 編譯器自動生成的就足夠了。 – 2012-07-26 01:20:11

+0

啊,謝謝。我沒有任何東西,只是沒有定義。我會這樣離開它。 =) – 2012-07-26 01:31:34

+0

@NedBatchelder這是否意味着在他的情況下,他不能刪除他的析構函數中的三個指針?因爲他的三分球都指向「卡車」不擁有的變數。 – shengy 2012-07-26 01:36:05

2

由於指針並沒有從類中分配,所以刪除和NULL都不會在這裏。由於指針是從課堂外傳遞過來的,因此請讓他們獨處。

事實上,你正在傳遞引用,然後將它們轉換成構造函數中的指針。這似乎沒有必要。可能更好地將它們用作內部參考。真的取決於你的用例。如果你想使用指針,可能是一個好主意,讓你的構造函數接受指針。顯式比隱式更好。

+0

謝謝你的回答!我受到一些限制,肯定會做得有點不同,但我會根據您的答案和Ned的答案將析構函數清空。 – 2012-07-26 01:32:36

相關問題