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?或删除它们?

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

感谢您的帮助,只是想养成创建适当析构函数的好习惯。

4

2 回答 2

6

当您在对象中存储指针时,您需要清楚地了解谁拥有它们指向的内存。如果您的类是所有者,则析构函数必须释放内存,否则您将发生泄漏。如果您的班级不是所有者,那么您不得释放内存。

将点设置为 NULL 是不必要的,重要的是正确处理内存本身。

管理指针的一种更简单的方法是使用智能指针类,它会自动为您处理。

于 2012-07-26T01:18:34.613 回答
2

由于您的指针不是从类内分配的,因此 delete 和 NULL 都不会在这里。由于指针是从类外部传递的,所以不要管它们。

实际上,您正在传递引用,然后将它们转换为构造函数中的指针。这似乎没有必要。可能更好地将它们用作内部参考。真的取决于你的用例。如果你想使用指针,让你的构造函数接受指针可能是个好主意。显式优于隐式。

于 2012-07-26T01:24:41.520 回答