C++ C++;,委托、应用程序崩溃、未知原因
我的代码有一个奇怪的问题,因为编译器生成的代码使我的测试应用程序崩溃。 我用Visual C++ 2010编译器。 代码是:C++ C++;,委托、应用程序崩溃、未知原因,c++,delegates,C++,Delegates,我的代码有一个奇怪的问题,因为编译器生成的代码使我的测试应用程序崩溃。 我用Visual C++ 2010编译器。 代码是: template < typename TDstType, typename TSrcType > TDstType unsafe_cast( TSrcType anySrc ) { return ( TDstType ) anySrc; } template < typename TDstType,
template < typename TDstType,
typename TSrcType >
TDstType unsafe_cast( TSrcType anySrc )
{
return ( TDstType ) anySrc;
}
template < typename TDstType,
typename TSrcType >
TDstType brutal_cast( TSrcType anySrc )
{
return *( TDstType* ) &anySrc;
}
template < typename TParamType >
class EventHandler
{
public:
template < typename TObjectType >
EventHandler( TObjectType& refObject,
void ( TObjectType::*pfnMethod )( TParamType ) );
void operator()( TParamType anyParam );
private:
void* m_ptrMethod;
void* m_ptrObject;
};
template < typename TParamType >
template < typename TObjectType >
inline EventHandler< TParamType >::EventHandler( TObjectType& refObject, void ( TObjectType::*pfnMethod )( TParamType ) )
: m_ptrMethod( brutal_cast< void* >( pfnMethod ) ),
m_ptrObject( &refObject )
{
}
template < typename TParamType >
inline void EventHandler< TParamType >::operator()( TParamType anyParam )
{
class Class;
( unsafe_cast< Class * >( m_ptrObject )->*
brutal_cast< void ( Class::* )( TParamType ) >( m_ptrMethod ) )( anyParam );
}
template
TDstType不安全类型转换(TSrcType anySrc)
{
返回(TDstType)anySrc;
}
模板
TDstType cast(TSrcType anySrc)
{
return*(TDstType*)&anySrc;
}
模板
类事件处理程序
{
公众:
模板
EventHandler(TObjectType和ReObject,
void(TObjectType::*pfnMethod)(TParamType));
void运算符()(TParamType anyParam);
私人:
void*m_p方法;
void*m_ptrObject;
};
模板
模板
内联事件处理程序::事件处理程序(TObjectType&ReObject,void(TObjectType::*pfnMethod)(TParamType))
:m_ptrMethod(残酷的施法(pfnMethod)),
m_ptrObject(重新对象和重新对象)
{
}
模板
内联void事件处理程序::运算符()(TParamType anyParam)
{
班级;
(不安全铸造(m_ptrObject)->*
残酷的施法(m\u ptrMethod))(anyParam);
}
以及测试应用程序的代码:
class SomeClass
{
public:
void Method( int intParam )
{
printf( "%d\n", intParam );
}
};
int main( int intArgc, char* arrArgv[] )
{
EventHandler< int > varEventHandler( *new SomeClass(), &SomeClass::Method );
varEventHandler( 10 );
return 0;
}
class-SomeClass
{
公众:
void方法(int intParam)
{
printf(“%d\n”,intParam);
}
};
int main(int intArgc,char*arrArgv[]
{
EventHandlervarEventHandler(*new SomeClass(),&SomeClass::Method);
varEventHandler(10);
返回0;
}
编译后的应用程序因试图从无效内存位置读取而崩溃。我在VisualStudio的调试器中检查了每个变量,没有一个包含无效地址。
我希望任何人都能帮我解决这个问题,因为我失败了。也许咖啡过量是原因…这不起作用;不能将指向成员的指针强制转换为void*。这样做会丢失信息,程序也会崩溃。老实说,我希望包含
野蛮强制转换和不安全强制转换的程序不会运行得很好。您的事件处理程序::操作符()
中的代码是什么?