简体   繁体   English

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

[英]Heap vs Stack memory usage C++ for dynamically created classes

If you create a class in C++ with non-pointer member variables and non-pointer member functions yet you initialize an instance of the class dynamically (using pointers) does memory usage come from the heap or the stack? 如果您使用非指针成员变量和非指针成员函数在C ++中创建类,但是您动态地(使用指针)初始化类的实例,内存使用是来自堆还是堆栈?

Useful info for a project I am working on as I am trying to reduce memory from the stack :). 我正在努力的项目的有用信息,因为我试图减少堆栈中的内存:)。

Any response is greatly appreciated. 非常感谢任何回应。

Many thanks and happy coding. 非常感谢和愉快的编码。

If you use operator new for allocating you class, than it is put on the heap. 如果使用operator new来分配类,则将它放在堆上。 Not matter if member variables are accessed by pointers or not. 无论成员变量是否被指针访问都无关紧要。

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

But be careful as not every instance accessed by a pointer may actually be located on the heap. 但要小心,因为指针访问的每个实例都不会真正位于堆上。 For example: 例如:

A a; // all members are on the stack
A* pa = &a; // accessed by pointer, but the contents are still not on the heap!

On the other side a class instance located on the stack may have most of its data on the heap: 另一方面,位于堆栈上的类实例可能在堆上拥有大部分数据:

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

如果使用“new”创建对象,则在堆中创建对象。

对于指针变量,内存将在stack分配,但是当您使用newmalloc ,该内存段将在heap分配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM