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.
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.
Share Improve this question edited Jan 18 at 14:06 trincot 351k36 gold badges272 silver badges325 bronze badges asked Jan 18 at 8:26 Rich GgRich Gg 612 bronze badges 5 |1 Answer
Reset to default 6class 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.
arr
is in the heap becausearr
is part ofObj
andobj
is pointing at a dynamically allocatedObj
. Same is true of your second question, for the same reason. – john Commented Jan 18 at 8:29arr
has automatic storage (stack), if the instance of Obj had dynamic storage thenarr
will have automatic storage too.obj
will always have dynamic storage – Pepijn Kramer Commented Jan 18 at 9:55std::endl
does. Use'\n'
to end a line unless you have a good reason not to. – Pete Becker Commented Jan 18 at 14:29