堆栈内存使用C++用于动态创建的类

Lou*_*zin 4 c++ pointers memory-management class

如果您使用非指针成员变量和非指针成员函数在C++中创建类,但是您动态地(使用指针)初始化类的实例,内存使用是来自堆还是堆栈?

我正在努力的项目的有用信息,因为我试图减少堆栈中的内存:).

非常感谢任何回应.

非常感谢和愉快的编码.

Dan*_*vil 8

如果使用运算符new来分配类,则将它放在堆上.无论成员变量是否被指针访问都无关紧要.

class A {
    int a;
    float* p;
};
A* pa = new A(); // required memory is put on the heap
A a; // required memory is put on the stack
Run Code Online (Sandbox Code Playgroud)

但要小心,因为指针访问的每个实例都不会真正位于堆上.例如:

A a; // all members are on the stack
A* pa = &a; // accessed by pointer, but the contents are still not on the heap!
Run Code Online (Sandbox Code Playgroud)

另一方面,位于堆栈上的类实例可能在堆上拥有大部分数据:

class B {
public:
    std::vector<int> data; // vector uses heap storage!
    B() : data(100000) {}
};
B b; // b is on the stack, but most of the memory used by it is on the heap
Run Code Online (Sandbox Code Playgroud)

  • 此外,在堆上分配具有静态存储持续时间的对象(例如,全局对象或静态本地对象) (2认同)