类的指针数组C ++的析构函数 [英] Destructor of class with pointer array C++

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

问题描述

如果我有一个类包含指向另一个类 Vehicle 的指针数组:

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

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

如果我现在写的类的析构函数 List ,我手动迭代数组(我知道在数组中有多少项)和 delete 每个指针指向一个车辆,或将C ++自动调用数组中所有车辆的析构函数?

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)

编辑:
我忘记了 delete [] vehicles 它会删除数组中所有车辆使用的内存,还是只删除指针所使用的内存?

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 ++的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆