我想在我的程序中提出一个简单的问题我制作某种系统,对于动态分配我正在使用像这样指针的指针数组
Vehicle **temp=new Vehical*[countVehicle];
然后
temp[countVehicle-1]=new Car();
你一定明白我要做的事。删除内存时出现问题。在这种情况下,你能否告诉我如何删除内存。
答案 0 :(得分:2)
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.
这将简化内存管理。
答案 1 :(得分:1)
如果您确定temp中的指针是NULL或有效的已分配Car,那么:
for(int i = 0; i < countVehicle; ++i)
delete temp[i];
delete[] temp;
只有在具有虚拟析构函数的情况下,这才能正常工作。否则你将无法正确销毁每辆车。