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

Deleting array of pointers to pointers pointing to object

本文关键字:指针 数组 对象 删除      更新时间:2023-10-16

我想问一个简单的问题在我的程序中我做了一些系统,对于动态分配我取一个指针指向指针的数组,像这样

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

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

你一定明白我在努力做什么。当删除内存时,问题就出现了。你能告诉我在这种情况下如何删除内存吗?

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

确保基类Vehicle中的析构函数声明为虚函数,以便在通过基类指针删除对象时调用正确的析构函数,就像上面的例子一样。

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

但是你应该考虑使用智能指针的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.

如果您确定temp中的指针为NULL或已分配的有效Car,则:

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

只有在Vehicle有虚析构函数时才会正确工作。