2012-03-21 101 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 *。這樣做會丟失信息和程序,毫不奇怪,崩潰。