我是 C++ 的新手,我想澄清一些关于使用运算符“new ...”和运算符“delete ...”进行内存管理的要点。
我会发布一些我的代码,如果我的评论有误,请您指正。
我也在处理虚函数和接口(interface),通过阅读代码就很清楚了,我也问你我是否以正确的方式接近它们。
那么我有一个更直接的问题,什么时候应该使用“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
分配的内存在 HEAP 上,其他所有东西都在堆栈上。所以在你的代码中,你有
vehicle* motorVehicle[2] = { new (car), new (motorcycle) };
栈上有两个指针 vehicle*[2]
的数组,堆上有两个对象,car
和 motocycle
.
然后你有两个循环
for (int i = 0; i < 2; i++)
在循环期间,每一个都在堆栈上创建一个整数。
关于C++ - 指向对象的指针数组,什么存储在 STACK 中,什么存储在 HEAP 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909180/