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
If you use 'new' to create an object the object is created in the heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With