删除指向对象指针的指针数组
Deleting array of pointers to pointers pointing to object
我想问一个简单的问题在我的程序中我做了一些系统,对于动态分配我取一个指针指向指针的数组,像这样
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有虚析构函数时才会正确工作。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空