Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor of class with pointer array 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?

(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?

like image 824
Aerus Avatar asked Dec 17 '22 18:12

Aerus


2 Answers

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.

like image 112
stefaanv Avatar answered Jan 02 '23 14:01

stefaanv


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.

like image 41
Nemanja Trifunovic Avatar answered Jan 02 '23 13:01

Nemanja Trifunovic