C++-指向对象的指针数组,存储在STACK中的内容和存储在HEAP中的内容
C++ - Array of pointers to object, what is stored in STACK and what in HEAP?
我对C++很陌生,我想用运算符"new…"和运算符"delete…"来澄清一些关于内存管理的要点。
我会发布一些我的代码,我问你是否可以纠正我的评论,如果他们是错误的。
我也在处理虚拟函数和接口,通过阅读代码可以清楚地看到,我还问你我是否以正确的方式处理它们。
然后我有一个更直接的问题,我应该在什么时候使用"new[]…"或"delete[]…",以及我应该如何正确使用它们?
PS:下面的代码输出是:
car built
motorcycle built
car has 4 wheels
motorcycle has 2 wheels
car destroyed
motorcycle destroyed
这是主要的.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++)
其中每一个在循环的持续时间内在堆栈上创建一个整数。
关于您的代码:指针数组是一个局部变量,其将被分配在堆栈上。他们指的是什么在你的例子中,selves指向的是分配的动态地(在堆上)。
关于"更直接的问题":我还没有找到任何案例其中应当使用CCD_ 5。它出现的原因完整性,但它并没有任何合理的用途。
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 将std::stack.pop()方法的结果存储到一个变量中
- 将Lua类对象存储到C指针,并将其推送回Lua Stack
- std::stack如何组织内部存储
- C++-指向对象的指针数组,存储在STACK中的内容和存储在HEAP中的内容