Heap memory usage for storing C ++ stack for dynamically created classes

If you create a C ++ class with non-pointer member variables and non-pointer functions, but you initialize the class instance dynamically (using pointers), does the memory use from the heap or stack?

Useful information for the project I'm working on when I try to reduce memory from the stack :).

Any answer is welcome.

Thanks a lot and happy coding.

+4
source share
3 answers

If you use an operator newto allocate a class, then it is placed in a heap. It doesn't matter if member variables are accessible 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

, , , . :

A a; // all members are on the stack
A* pa = &a; // accessed by pointer, but the contents are still not 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
+8

"" , .

+1

for memory variable variables the pointer will be allocated to stack, but when you use newor malloc, then this segment of memory will be allocated toheap

0
source

Source: https://habr.com/ru/post/1533336/


All Articles