C++ - 指向对象的指针数组,什么存储在 STACK 中,什么存储在 HEAP 中?

标签 c++ arrays pointers heap-memory stack-memory

我是 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] 的数组,堆上有两个对象,carmotocycle.

然后你有两个循环

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

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

关于C++ - 指向对象的指针数组,什么存储在 STACK 中,什么存储在 HEAP 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909180/

相关文章:

c++ - 基于对话框的 Win32 API 程序在使用 Richedit 控件时不会显示窗口

c++ - 超出最大数字类型大小的枚举

javascript - 将数组分割成一定长度的n个数组

C++ - 使用临时变量索引数组

c++ - 智能指针和复制构造函数

c++ - LNK2019:OpenCV 中未解析的外部符号

java - 如何用Java从文本文件中读取格式化数据

Cython:将 void* 转换为 double 和反向转换

c++ - 为什么 C++ 允许通过指针访问类的私有(private)成员?

c++ - 从不同的字节中提取和组合位 c c++