简体   繁体   English

删除指向指向对象的指针的指针数组

[英]Deleting array of pointers to pointers pointing to object

I want to ask one simple question in my program i making some kind of system, for dynamic allocation I am taking array of pointers to pointers like this我想在我的程序中问一个简单的问题,我正在制作某种系统,对于动态分配,我正在使用指向这样的指针的指针数组

Vehicle **temp=new Vehical*[countVehicle];

then然后

temp[countVehicle-1]=new Car();

You must have understood what I am trying to do.你一定已经明白我要做什么了。 The problem comes when deleting memory.删除内存时出现问题。 Can you please tell me how to delete memory in this case.你能告诉我在这种情况下如何删除内存吗?

for ( int i = 0; i < countVehicle; ++i)
{
    delete temp[i];  // assert destructor is virtual!
}
delete[] temp;

Make sure destructor in base class, Vehicle , is declared virtual so the correct destructor is called when deleting objects via base class pointer, as it take place in example above.确保基类Vehicle析构函数被声明为 virtual 以便在通过基类指针删除对象时调用正确的析构函数,如上面的示例中发生的那样。

class Vehicle {
public:
    //...
    virtual ~Vehicle() {}
};

However you should consider using a std::vector of smart pointers, eg但是,您应该考虑使用智能指针的std::vector ,例如

{
  std::vector< boost::shared_ptr<Vehicle> > v;
  v.push_back( boost::shared_ptr<Vehicle>( new Car()));
  v[0]->run(); // or whatever your Vehicle can do
  //...
} // << When v goes out of scope the memory is automatically deallocated.

This will ease memory management.这将简化内存管理。

If you know for sure that the pointers in temp are NULL or a valid allocated Car then:如果您确定 temp 中的指针为 NULL 或有效分配的 Car 则:

for(int i = 0; i < countVehicle; ++i)
    delete temp[i];
delete[] temp;

This will only work correctly if Vehicle has a virtual destructor.只有当 Vehicle 具有虚拟析构函数时,这才能正常工作。 Otherwise you will not properly destroy each Car.否则,您将无法正确销毁每辆汽车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM