Sign in to follow this  
Red Ant

reinterpret_cast weirdness

Recommended Posts

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";
    }
   
    // ...  
}

Share this post


Link to post
Share on other sites
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 float
float & rf2 = *reinterpret_cast< float * >(&x); // OK. rf2 == bit pattern of x interpreted as a float
float & rf3 = *reinterpret_cast< float * >(px); // OK. rf3 == bit pattern of x interpreted as a float
float & rf4 = reinterpret_cast< float & >(px); // NOT OK. rf4 == bit pattern of address of x interpreted as a float
float & rf5 = *reinterpret_cast< float * >(&px); // NOT OK. rf5 == bit pattern of address of x interpreted as a float
float * pf = reinterpret_cast< float * >(px); // OK. *pf == bit pattern of x interpreted as a float


Enigma

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this