.net 调用析构函数时的循环依赖关系
我有以下体系结构,并且由于继承,在类上调用析构函数时,它会导致循环依赖.net 调用析构函数时的循环依赖关系,.net,dependencies,c++-cli,destructor,circular-dependency,.net,Dependencies,C++ Cli,Destructor,Circular Dependency,我有以下体系结构,并且由于继承,在类上调用析构函数时,它会导致循环依赖 namespace IntOp { ref class PwItem; ref class PwTag; public ref class PwItem { public: PwItem(void* arg1, <sometype>arg2, unsigned __int64 arg3); { // some constructor work
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();
}}
实际GetItem函数
我相信你们正在努力创建一个工厂。但这是一个相当不寻常的工厂。您说过基类根据请求的对象类型创建子类实例。但您的代码正在做其他事情。 每个子类总是有一个实例吗?另外,对于每个子类,是否将其对象保留在基类PwItem中? 另外,CreateItem方法中没有提到它,您需要哪个子实例! 假设出现了一个PwXYZ子类,那么您的代码是什么? 我看到的一个错误是,您正在静态函数中发送PwTag的非静态实例 基类中所需的只是一个静态CreateInstance方法,该方法将采用请求的对象类型并返回该对象。不需要在基类中保留任何子类对象
//You can have an ENUM >>> enum ItemType { PwTag,... so on};
static PwItem* PwItem::CreateItem(ItemType type){
//check which type of object is requested and simply return the instance
}
另外,基类应该有一个VIRTUALpublic析构函数。由于您正在发送子类的基引用,如果您试图删除它并删除具有基引用的子对象,则会导致内存泄漏,因为不会调用子类的析构函数
那么,现在你的基类就是
...
public:
PwItem();
virtual ~PwItem(){};
static PwItem^ PwItem::CreateItem(ItemType type)
{
//switch cases OR IFs whatever you like...
//return instance of the object requested
}
...
希望这能有所帮助。这个设计是我继承的,正在导致泄漏。其思想是,有人使用CreateObject请求一个PwItem对象,在该函数中,确定该对象是正在查找的PwTag,因此创建并返回一个新的PwTag对象。基本上,基类用于实例化派生类的对象,并以这种方式返回。不幸的是,假设在while循环中调用CreateItem之类的东西,就会导致内存泄漏。有没有办法在不大修这个体系结构的情况下改变它?我已经添加了一些代码来让它更清晰一些。实际上,我在基类中没有子类对象,它只是返回gcnew,但是由于泄漏,我想显式地调用子类指针上的delete,这就是为什么我在基类中使用子类的对象。他们继续轮流呼叫对方的破坏者,但都没用。每次刷新仍会以8 kb的速度泄漏内存。如果我将PwItem构造函数保持私有,那么子类(在本例中为PwTag)将如何在其自己的构造函数中访问它?PwTagvoid*arg1,arg2,未签名的_int64 arg3:pwtigem void*arg1,arg2,未签名的_int64 arg3{};。是的,我的观点是正确的,因为你没有对PwItem类做任何事情,你正在向它发送参数。。。现在我想您希望在PwItem中添加一些常见功能。现在只剩下日志了。
//You can have an ENUM >>> enum ItemType { PwTag,... so on};
static PwItem* PwItem::CreateItem(ItemType type){
//check which type of object is requested and simply return the instance
}
...
public:
PwItem();
virtual ~PwItem(){};
static PwItem^ PwItem::CreateItem(ItemType type)
{
//switch cases OR IFs whatever you like...
//return instance of the object requested
}
...