C++-指向对象的指针数组,存储在STACK中的内容和存储在HEAP中的内容

C++ - Array of pointers to object, what is stored in STACK and what in HEAP?

本文关键字:存储 STACK HEAP 对象 指针 数组 C++-      更新时间:2023-10-16

我对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。它出现的原因完整性,但它并没有任何合理的用途。