与指针数组C级的析构函数

与指针数组C级的析构函数

本文介绍了与指针数组C级的析构函数++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个指针数组类到另一个类的汽车的:

If I have a class with an array of pointers to another class Vehicle :

class List {
    public:
        //stuff goes here
    private:
        Vehicle ** vehicles;
}

如果我现在写的类列表的析构函数,我手动数组上迭代(我知道有多少项目是数组中)和删除每个指针车辆,还是会自动ç++调用所有车辆的析构函数在数组中?

If I now write the destructor of the class List, do I manually iterate over the array (I know how many items are in the array) and delete every pointer to a vehicle, or will C++ automatically call the destructors of all the Vehicles in the array?

(像它是否有一个私人的字符串/ ...在类或者如果它是车辆指针的STL容器)

(Like it does if there's a private string/... in the class or if it would be a STL container of Vehicle pointers)

编辑:
我忘了删除[]车,但如果我要做到这一点,将它也删除阵列中使用的所有车辆的内存,或者它只是删除存储由指针使用呢?

I forgot about delete [] vehicles, but if I would do that, would it also delete the memory used by all the vehicles in the array, or would it just delete the memory used by the pointers?

推荐答案

您需要删除阵列中的所有条目,并删除阵列。
目前在C ++的方法(STL),以避免这种情况:使用矢量,所以您不必删除阵列。使用每辆车的scoped_ptr / shared_ptr的,所以您不必删除车辆。

You have to delete all the entries in the array AND delete the array.There are methods in C++ (STL) to avoid this: use a vector, so you don't have to delete the array. Use scoped_ptr/shared_ptr per Vehicle, so you don't have to delete the vehicles.

这篇关于与指针数组C级的析构函数++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:40