具有指针数组的类的析构函数 C++
如果我有一个类,其中包含指向另一个类 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须删除数组中的所有条目并删除该数组。
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.
如果 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.
vehicles
不是一个指针数组,而是一个指向Vehicle
类型的指针。指针数组的定义类似于
Vehicle* cars[N]
。是的!您不希望您的代码泄漏内存,是吗?
我建议使用 Boost 库中的
Boost::scoped_ptr
。此外,如果您的编译器支持 C++0x,您还可以使用std::unique_ptr
vehicles
is not an array of pointers rather its a pointer to pointer to aVehicle
type.An array of pointers would be defined something like
Vehicle* vehicles[N]
.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 usestd::unique_ptr
您必须手动迭代车辆并
删除
每一个车辆。You have to manually iterate over vehicles and
delete
each and every of them.