【发布时间】:2013-07-28 08:47:06
【问题描述】:
我是 C++ 的新手,我想澄清一些关于使用运算符“new ...”和运算符“delete ...”的内存管理的要点。
我会发布一些我的代码,如果有错误,请您纠正我的 cmets。
我也在处理虚函数和接口,这通过阅读代码很清楚,我还问你我是否以正确的方式接近它们。
那我有一个更直接的问题,什么时候应该使用“new[] ...”或“delete[] ...”,应该如何正确使用?
PS:下面代码的输出是:
car built
motorcycle built
car has 4 wheels
motorcycle has 2 wheels
car destroyed
motorcycle destroyed
这是main.cpp的来源:
#include <iostream>
using namespace std;
class vehicle
{
public:
virtual
~vehicle()
{
}
virtual void
wheelNum() = 0;
};
class car : public vehicle
{
public:
car()
{
cout << "car built" << endl;
}
~car()
{
cout << "car destroyed" << endl;
}
void
wheelNum()
{
cout << "car has 4 wheels" << endl;
}
};
class motorcycle : public vehicle
{
public:
motorcycle()
{
cout << "motorcycle built" << endl;
}
~motorcycle()
{
cout << "motorcycle destroyed" << endl;
}
void
wheelNum()
{
cout << "motorcycle has 2 wheels" << endl;
}
};
int
main()
{
// motorVehicle[2] is allocated in the STACK and has room for 2 pointers to vehicle class object
// when I call "new ...", I allocate room for an object of vehicle class in the HEAP and I obtain its pointer, which is stored in the STACK
vehicle* motorVehicle[2] = { new (car), new (motorcycle) };
for (int i = 0; i < 2; i++)
{
// for every pointer to a vehicle in the array, I access the method wheelNum() of the pointed object
motorVehicle[i] -> wheelNum();
}
for (int i = 0; i < 2; i++)
{
// given that I allocated vehicles in the HEAP, I have to eliminate them before terminating the program
// nevertheless pointers "motorVehicle[i]" are allocated in the STACK and therefore I don't need to delete them
delete (motorVehicle[i]);
}
return 0;
}
谢谢大家。
【问题讨论】:
-
对于每个
new T,您需要一个delete,对于每个new T[...],您需要一个delete []。你的代码看起来不错。 -
您发布的代码运行良好。考虑使用智能指针,例如
std::shared_ptr或std::unique_ptr,用于管理堆分配内存的生命周期。 -
如果我使用 new[] 分配 motorVeichle[2] 会怎样?我应该声明一个指向指针数组的指针吗?
-
不,
new[]返回一个指向第一个元素的指针,因此您仍然需要声明一个指向车辆的指针:vehicle* p = new vehicle[2];。请记住使用delete[]将其删除。如果要分配数组数组,则需要一个指向数组的指针:int(*p)[5] = new int[5][x]; -
@iMineLink 你不应该。什么场景需要
new[]?
标签: c++ arrays pointers heap-memory stack-memory