什么应该在适当的析构函数?

tf.*_*.rz 2 c++ destructor memory-management

我知道析构函数本质上是一个释放内存的函数,或者只要你完成它就会"清理".

我的问题是,正确的析构函数是什么?

让我给你看一些我所拥有的课程的代码:

#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.

};
Run Code Online (Sandbox Code Playgroud)

这是构造函数:

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
Run Code Online (Sandbox Code Playgroud)

在我的析构函数类中,我应该在指针后清理吗?也就是说,将它们设置为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
Run Code Online (Sandbox Code Playgroud)

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

Ned*_*der 6

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

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

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