下面的代码创建一个指向 a 的双B**
指针B*
。它将使用该指针为另一个指针分配内存,该指针将指向调用B
时创建的实例start()
:
class A
:
class A
{
public:
A()
{
fb = new B*;
*fb = NULL;
}
~A()
{
if(*fb)
delete *fb;
delete fb;
}
B** getfb()
{
return fb;
}
private:
B** fb;
};
class B
:
class B
{
public:
B()
{
B** fb = a->getfb();
*fb = this;
}
~B()
{
B** fb = a->getfb();
delete *fb; // <--- stack overflow
*fb = NULL;
}
private:
A* a;
};
start()
(的成员函数class C
):
void C::start()
{
B** fb = a->getfb(); // 'a' is a pointer to an 'A' instance
if(*fb == NULL)
B* f = new B;
}
所以,每当我调用start()
然后调用~B()
时,我都会遇到堆栈溢出!