【发布时间】:2014-08-03 14:02:40
【问题描述】:
我有以下架构,并且由于继承,当在类上调用destructors 时会导致循环依赖。
namespace IntOp
{
ref class PwItem;
ref class PwTag;
public ref class PwItem
{
public:
PwItem(void* arg1, <sometype>arg2, unsigned __int64 arg3);
{
// some constructor work
}
virtual ~PwItem(){};
static PwItem^ PwItem::CreateItem(void* arg1, <sometype>arg2, unsigned __int64 arg3)
{
if(arg2 is of type PTag)
{ // PTag = gcnew PwTag(arg1, arg2, arg3);
// return PTag;
return gcnew PwTag(arg1, arg2, arg3);
}
else if(arg2 is of type PFile)
{ //PFile = gcnew PwTag(arg1, arg2, arg3);
// return PFile;
return gcnew PwFile(arg1, arg2, arg3);
}
return gcnew PwItem(arg1, arg2, arg3);
}
private :
//PwTag^ PTag;
// PwFile^ PFile; //Another type with PwItem as Base constructor
}
public ref class PwTag : PwItem
{
public:
PwTag(void* arg1, <sometype>arg2, unsigned __int64 arg3) : PwItem (void* arg1, <sometype>arg2, unsigned __int64 arg3) {};
virtual ~PwTag();
}}
所以这里,当我想在PwItem上调用一个delete,所以它释放了PwItem的实例化,然后因为继承,PwTag在PwItem上调用了destructor,整个事情不断重复。
如何解决这个问题? destructor 确实需要被调用来释放类对象中的一些东西。
编辑:添加调用代码
myServer srv = new myServer();
srv.connect();
while(true)
{
PwItem ^item = srv.GetItem(<some string>); //This will invoke the GetItem function, which will call createItem()
System.Threading.Thread.Sleep(200);
}
实际的 GetItem() 函数
PwItem^ myServer::GetItem(<some string>)
{
// do some work, nothing new being instantiated etc. just arguments 1, 2 and 3, which do not cause leaks
return gcnew PwItem::CreateItem(arg1, arg2, arg3);
// Tried instantiating a PwItem pi; return pi.CreateItem(arg1, arg2, arg3); as well. No luck
// Bypassed PwItem entirely, and based on arg2, called return gcnew PwTag(arg1, arg2, arg3); as well, no luck
// Tried PwItem pi, ^tempPwItem; tempPwItem = pi.CreateItem(arg1, arg2, arg3); return tempPwItem; No luck
}
【问题讨论】:
标签: .net dependencies c++-cli destructor circular-dependency