Destructor of class with pointer array C++

2019-05-03 12:04发布

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?

4条回答
成全新的幸福
2楼-- · 2019-05-03 12:37

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.

查看更多
唯我独甜
3楼-- · 2019-05-03 12:44

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

查看更多
叛逆
4楼-- · 2019-05-03 12:53

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

查看更多
老娘就宠你
5楼-- · 2019-05-03 12:55

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.

查看更多
登录 后发表回答