A引用B,B引用A,导致对方引用计数增加,内存释放可能出现问题,大体这样。
下面是一个例子:
//以下出现的类继承自Object
//Object中提供retain(引用计数增1)和release(引用计数减1)操作,
//autoRelease操作将该对象的存储释放工作交给辅助对象处理
class FPC_DLL DisplayObject:public EventDispatcher
{
public:
void setParent(DisplayObjectContainer* parent)
{
pParent_ = parent;
pParent_.retain(); //循环引用,引用计数出现问题
} }
class FPC_DLL DisplayObjectContainer:public DisplayObject
{
private:
Array* pChildren_;public:
~DisplayObjectContainer()
{
pChildren_.release();
}
void addChildAt(DisplayObject* child,uint32 index)
{
child->retain();
child->setParent(this);
//内含对child的retain操作
pChildren_->insertObject(child,FPC_MIN(pChildren_->count(),index));
child->release();
} }
////////////////////////////////////////////////////////////////
{
DisplayObject* do = new DisplayObject;
DisplayObjectContainer* doc = new DisplayObjectContainer;
do.autoRelease();
doc.autoRelease();
doc.addChild(do);
//辅助对象释放存储可能出现问题
}
这里的问题还是比较直观的,还好解决,如果涉及的对象多一些,可能不是那么好发现了。
--
Milo Yip
http://www.cnblogs.com/miloyip/
http://weibo.com/miloyip/
http://twitter.com/miloyip/