Destructor of class with pointer array C++

血红的双手。 提交于 2019-12-05 18:13:17

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.

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!