reinterpret_cast weirdness

Started by
2 comments, last by Enigma 18 years, 5 months ago
Hi all, I've stumbled across a very strange problem (using MS VC++ 6.0) where I get a void pointer passed into a function. I know the exact type of the object beforehand (have to use void pointers .... I'm writing a plugin for the Tcl interpreter API) so I can just cast it from void to the actual type of object pointed to and then do stuff with it. Now, I figured that since I'm not going to do any pointerish things with the object, I might just as well cast it to a reference rather than a pointer. However, this caused an access violation whenever I accessed one of the methods of the object ... and the object looks all wrong in the debugger. I then compared the address of the referenced object to the value of the void pointer ... and they were not the same!! Then I decided to just cast the void pointer to a pointer of the same type as my class ... and suddenly it worked! And the addresses are matching as they should as well! What the frig?? Is it not legal to cast a pointer to a reference??

void myFunc( void* pInstanceOfClassA )
{
    assert( pInstanceOfClassA != 0x00 );
    ClassA& rInstance = reinterpret_cast < ClassA& > ( pInstanceOfClassA );
    ClassA* pInstance = reinterpret_cast < ClassA* > ( pInstanceOfClassA );

    // This crashes!
    rInstance.myMethod();

    // This works.
    pInstance->myMethod();

    // This is not true.
    if ( &rInstance == pInstanceOfClassA )
    {
        std::cout << "Addresses are matching.\n";
    }

    // But this is.
    if ( pInstance == pInstanceOfClassA )
    {
        std::cout << "Addresses are matching.\n";
    }
   
    // ...  
}
Advertisement
have you tried something like this:

ClassA& rInstance = *(reinterpret_cast< ClassA* >( pInstanceOfClassA ) );

should work
Yeah, that works. I'm just a little puzzled why my initial approach didn't work.
reinterpret_cast< T & >(x) is equivalent to *reinterpret_cast< T * >(&x), whereas you are wanting reinterpret_cast< T & >(x) to mean the equivalent of reinterpret_cast< T >(*x). I.e.:
int x;int * px = &x;float & rf1 = reinterpret_cast< float & >(x); // OK.  rf1 == bit pattern of x interpreted as a floatfloat & rf2 = *reinterpret_cast< float * >(&x); // OK.  rf2 == bit pattern of x interpreted as a floatfloat & rf3 = *reinterpret_cast< float * >(px); // OK.  rf3 == bit pattern of x interpreted as a floatfloat & rf4 = reinterpret_cast< float & >(px); // NOT OK.  rf4 == bit pattern of address of x interpreted as a floatfloat & rf5 = *reinterpret_cast< float * >(&px); // NOT OK.  rf5 == bit pattern of address of x interpreted as a floatfloat * pf = reinterpret_cast< float * >(px); // OK.  *pf == bit pattern of x interpreted as a float


Enigma

This topic is closed to new replies.

Advertisement