Reputation: 83
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.
Upvotes: 4
Views: 177
Reputation: 22991
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
Upvotes: 8
Reputation: 1361
for the pointer variable memory will be allocated in stack
but when you are using new
or malloc
then that memory segment will be allocated in heap
Upvotes: 0
Reputation: 10415
If you use 'new' to create an object the object is created in the heap.
Upvotes: 1