具有指针数组的类的析构函数 C++

发布于 2024-10-13 00:48:21 字数 399 浏览 4 评论 0原文

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

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

如果我现在编写类 List 的析构函数,我是否需要手动迭代该数组(我知道数组中有多少项)并删除每个指向车辆的指针,或者 C++ 会自动调用数组中所有车辆的析构函数吗?

(就像类中存在私有字符串/...或者它是车辆指针的 STL 容器一样)

编辑: 我忘记了删除[]车辆,但如果我这样做,它是否也会删除数组中所有车辆使用的内存,或者只是删除指针使用的内存?

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?

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

EDIT:
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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

江南烟雨〆相思醉 2024-10-20 00:48:21

您必须删除数组中的所有条目并删除该数组。
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.

撩起发的微风 2024-10-20 00:48:21

如果 List 拥有 Vehicle 对象(在构造函数中创建它们),则需要删除每个对象,然后删除指针数组本身。

If the List owns Vehicle objects (creates them in the constructor) you need to delete every single one and then delete the array of pointers itself.

无法回应 2024-10-20 00:48:21

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

车辆 ** 车辆;

vehicles 不是一个指针数组,而是一个指向 Vehicle 类型的指针。
指针数组的定义类似于 Vehicle* cars[N]

我是否手动迭代数组(我知道数组中有多少项)并删除指向车辆的每个指针

是的!您不希望您的代码泄漏内存,是吗?

我建议使用 Boost 库中的 Boost::scoped_ptr 。此外,如果您的编译器支持 C++0x,您还可以使用 std::unique_ptr

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

Vehicle ** vehicles;

vehicles is not an array of pointers rather its a pointer to pointer to a Vehicle type.
An array of pointers would be defined something like Vehicle* vehicles[N].

do i manually iterate over the array (i know how many items are in the array) and delete every pointer to a vehicle

Yes! You dont want your code to leak memory do you?

I would recommend using Boost::scoped_ptr from the Boost library. Moreover if you compiler supports C++0x you can also use std::unique_ptr

朮生 2024-10-20 00:48:21

您必须手动迭代车辆并删除每一个车辆。

You have to manually iterate over vehicles and delete each and every of them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文