Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
Louie Mazin Avatar asked Jan 11 '23 22:01

Louie Mazin


2 Answers

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
like image 63
Danvil Avatar answered Jan 22 '23 05:01

Danvil


If you use 'new' to create an object the object is created in the heap.

like image 34
ScottMcP-MVP Avatar answered Jan 22 '23 03:01

ScottMcP-MVP