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

时间:2013-07-28 14:24:17

标签: c++ arrays pointers stack heap

我是C ++的新手,我希望使用运算符“new ...”和运算符“delete ...”清楚地说明有关内存管理的一些观点。

我会发布一些我的代码,如果他们错了,我会问你是否会纠正我的意见。

我也正在处理虚拟功能和界面,通过阅读代码可以清楚地看到,我也会问你是否正确地接近它们。

然后我有一个更直接的问题,我什么时候应该使用“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;
}

谢谢大家。

2 个答案:

答案 0 :(得分:2)

new分配的内存在HEAP上,堆栈中的其他内容。所以在你的代码中,你有

vehicle* motorVehicle[2] = { new (car), new (motorcycle) };

在堆栈上有一个由两个指针vehicle*[2]组成的数组,在堆上有两个对象,carmotocycle

然后你有两个循环

for (int i = 0; i < 2; i++)

每个都在循环的持续时间内在堆栈上创建一个整数。

答案 1 :(得分:1)

关于你的代码:指针数组是一个局部变量, 将在堆栈上分配。什么指针他们 在你的例子的情况下,自我指向是分配的 动态地(在堆上)。

关于“更直接的问题”:我还没有找到任何案例 应该使用new[]。它出现的原因 完整性,但它没有任何合理的用途。