什么应该在一个适当的析构函数中
What should be in a proper destructor?
我知道析构函数本质上是一个释放内存或在处理完内存后进行"清理"的函数。
我的问题是,在一个合适的析构函数中会发生什么?
让我给你看一些我有一个类的代码:
#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都不在这里。由于指针是从类外传递的,所以不要理会它们。
事实上,您正在传递引用,然后在构造函数中将它们转换为指针。这似乎没有必要。也许最好在内部使用它们作为参考。实际上取决于您的用例。如果你想使用指针,那么让你的构造函数接受指针可能是个好主意。显式比隐式好。
相关文章:
- 有一个构造函数,但有两个析构函数
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- 析构函数调用c++中的一个向量
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 在两个类上协调析构函数,其中一个类需要首先清理
- 在删除另一个类中的一个类的对象时析构函数如何工作
- 如何在另一个类的向量中调用派生类的析构函数
- 触发的断点(析构函数)与类模板类型是自身的一个版本
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 为什么复制构造函数不是微不足道的,因为有一个用户定义的析构函数?
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 这个递归类需要一个自定义析构函数?
- 如果我在析构函数中创建一个对象,会发生什么
- 是否可以在另一个类的实例中显式调用对象的析构函数?
- 设计一个没有虚拟析构函数的多态类层次结构
- 在这种情况下,我的派生类是否还需要一个虚拟析构函数
- 一个对象在析构函数中获取互斥以防止删除它自己
- 我可以有一个~析构函数(void)吗?
- 在C++中,如何编写一个析构函数来释放指向结构的指针的内存
- 有什么技巧可以检测对象是否是在执行另一个析构函数时创建的