Let's say we have 4 classes as follows:
class A
{
public:
A(void) : m_B()
{
}
private:
B m_B;
}
class B
{
public:
B(void)
{
m_i = 1;
}
private:
int m_i;
}
class C
{
public:
C(void)
{
m_D = new D();
}
~C(void)
{
delete m_D;
}
private:
D *m_D;
}
class D
{
public:
D(void)
{
m_i = 1;
}
private:
int m_i;
}
Lets say there are 4 cases:
case 1: A externally allocated on the stack, B internally allocated on the stack
A myA1;
case 2: A externally allocated on the heap, B internally allocated on the stack
A *myA2 = new A();
case 3: C externally allocated on the stack, D internally allocated on the heap
C myC1;
case 4: C externally allocated on the heap, D internally allocated on the heap
C *myC2 = new C();
What goes on in each of these cases? For example, in case 2, I understand the pointer myA2 is allocated on the stack, the A object exists in the heap, but what about the m_B attribute? I assume space on the heap allocated for it as well because it wouldn't make sense for an object to exist in heap space and then it's attribute goes out of scope. If this is true then does that mean the external heap allocation overrides the internal stack allocation?
What about case 3, myC1 is allocated on the stack, however m_D is allocated on the heap. What happens here? Are the two parts split across memory? If I removed the 'delete m_D' from the destructor and myC1 went out of scope, would there be a memory leak for the space allocated on the heap for m_D?
If there are any tutorials/articles that go over this in detail I would love a link.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…