c++heap-memorystack-memory

Is arr in stack or heap?


I want to understand if arr here is in stack or heap. Since obj is dynamically allocated is the arr in heap? What if i do not have obj2, if i just allocate obj dynamically in main?


#include <iostream>
#include <memory>
class Obj {
public:
    double arr[10000];
    Obj() {
        std::cout << "Obj Constructor" << std::endl;
    }
    ~Obj() {
        std::cout << "Obj Destructor" << std::endl;
    }
};
class Obj2 {
public:
    Obj2() {
        obj = std::make_unique<Obj>(); 
    }
    ~Obj2() {
        std::cout << "Obj2 Destructor" << std::endl;
    }
private:
    std::unique_ptr<Obj> obj; 
};
int main() {
    Obj2 obj2; 
    return 0;
}

Program runs and complies as should.


Solution

  • class member arrays are placed in the same storage as their containing class or struct, the array is a subobject.

    You allocated Obj on the heap with std::make_unique<Obj>();, therefore the array inside it is placed on the heap.

    if you want a dynamic array member that automatically gets placed on the heap regardless of its parent's storage then use std::vector, which is recommended if you have large arrays to avoid a stack overflow.