以下测试代码演示了我在更大的应用程序中遇到的问题。在应用程序中,我有一项服务“提供”了几个服务器,这些服务器都派生自一个基类。然后,我使用 createInstance 根据服务器类型(下面使用的“n”)“访问”特定服务器。然后使用 dynamic_cast 转换为适当的服务器。这一切都很好。
问题是当我尝试使用 deleteInstance 返回服务并删除它时,清理任何内部服务器相关数据。我似乎找不到一个好的传递机制,或者它是否是实现我正在做的事情的有效方式。
#include <iostream>
#include <string>
class MM
{
public:
virtual ~MM() {}
virtual void start() = 0;
};
class M1 : public MM
{
public:
void start()
{
std::cout << "M1 start" << std::endl;
}
};
class M2 : public MM
{
public:
void start()
{
std::cout << "M2 start" << std::endl;
}
void start( const std::string strName )
{
std::cout << "M2 start - " << strName << std::endl;
}
};
MM * createInstance( int n )
{
if( 2 == n )
{
return new M2;
}
else
{
return new M1;
}
}
void deleteInstance( MM * & pInstance )
{
delete pInstance;
pInstance = NULL;
}
void deleteInstance2( MM ** ppInstance )
{
delete *ppInstance;
*ppInstance = NULL;
}
int main( int argc, char *argv[] )
{
M1 *pM1 = dynamic_cast<M1 *>( createInstance( 1 ) );
M2 *pM2 = dynamic_cast<M2 *>( createInstance( 2 ) );
pM1->start();
pM2->start();
pM2->start( "test" );
deleteInstance( pM1 );
deleteInstance( pM2 );
//deleteInstance2( &pM1 );
//deleteInstance2( &pM2 );
return 0;
}
要完成信息,我收到的 deleteInstance 实现错误:
68:25: error: invalid initialization of reference of type ‘MM*&’ from expression of type ‘M1*’
46:6: error: in passing argument 1 of ‘void deleteInstance(MM*&)’
69:25: error: invalid initialization of reference of type ‘MM*&’ from expression of type ‘M2*’
46:6: error: in passing argument 1 of ‘void deleteInstance(MM*&)’
对于 deleteInstance2:
70:27: error: invalid conversion from ‘M1**’ to ‘MM**’
70:27: error: initializing argument 1 of ‘void deleteInstance2(MM**)’
71:27: error: invalid conversion from ‘M2**’ to ‘MM**’
71:27: error: initializing argument 1 of ‘void deleteInstance2(MM**)’