我知道析构函数本质上是一个释放内存或在完成后进行“清理”的函数。
我的问题是,适当的析构函数中有什么?
让我向您展示一些我拥有的课程的代码:
#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?或删除它们?
IE
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
感谢您的帮助,只是想养成创建适当析构函数的好习惯。