0

我对 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;
}

谢谢大家。

4

2 回答 2

3

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

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

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

然后你有两个循环

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

每个都在循环期间在堆栈上创建一个整数。

于 2013-07-28T14:38:31.237 回答
1

关于您的代码:指针数组是一个局部变量,将在堆栈上分配。在您的示例中,它们自己指向的指针是动态分配的(在堆上)。

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

于 2013-07-28T14:50:05.020 回答