什么应该在一个适当的析构函数中

What should be in a proper destructor?

本文关键字:一个 析构函数 什么      更新时间:2023-10-16

我知道析构函数本质上是一个释放内存或在处理完内存后进行"清理"的函数。

我的问题是,在一个合适的析构函数中会发生什么?

让我给你看一些我有一个类的代码:

#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

谢谢你的帮助,我只是想养成一个创建正确析构函数的好习惯。

当您在对象中存储指针时,您需要清楚地了解指针所指向的内存的所有者。如果您的类是所有者,则析构函数必须释放内存,否则就会发生泄漏。如果您的类不是所有者,则不能解除分配内存。

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

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

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

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

相关文章: