简体   繁体   中英

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?

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. 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分配

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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