2012-03-21 73 views
1

我的代码有一个奇怪的问题,因为编译器生成的代码会崩溃我的测试应用程序。 我正在使用Visual C++ 2010编译器。 的代码是:C++,代表,应用程序崩溃,未知原因

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); 
} 

和测试应用程序的代码:

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; 
} 

编译应用程序崩溃,因为它试图从一个无效的内存位置读取。我检查了Visual Studio的调试器中的每个变量,但都没有包含无效地址。 我希望任何人都可以帮我解决这个问题,因为我失败了。也许咖啡过量是因为...

+5

我说实话,我宁可期待一个包含'brutal_cast'和'unsafe_cast'的程序不能很好地工作。 – 2012-03-21 21:13:25

+0

你的'EventHandler :: operator()'中的代码是什么? – Jason 2012-03-21 21:13:32

+0

它在哪里以及如何崩溃? – bitmask 2012-03-21 21:15:37

回答

2

这不能工作;你不能将指向成员的指针转换为void *。这样做会丢失信息和程序,毫不奇怪,崩溃。