我知道一個析構函數本質上是一個釋放內存的函數,或者每當你完成它的時候就進行一次「清理」。什麼應該在一個合適的析構函數中?
我的問題是,什麼在一個適當的析構函數?
讓我告訴你一類我有一些代碼:
#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
感謝您的幫助,只是想在創造適當的析構函數的好習慣。
這取決於你的構造函數中有什麼。請參閱:[三條法則是什麼?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree) – Mysticial 2012-07-26 01:17:21
謝謝您的參考。我一定會看看。我已經添加了構造函數供您查看。 – 2012-07-26 01:19:40
看完奈德的回答後,我想你明白了,但我想說的是你可能想在使用前檢查你的指針,因爲有可能是'打印機'的主人刪除它,'卡車'不知道,並且那會導致崩潰。 – shengy 2012-07-26 01:38:46