简体   繁体   中英

C++ reinterpret_cast

I don't know why this simple code is not working:

int main()
{
    const char* c = "ret";
    typedef unsigned char GOK_UINT8;
    typedef GOK_UINT8* pGOK_UINT8;
    const pGOK_UINT8  y = reinterpret_cast<const GOK_UINT8*>(c);
    
    return 0;
}

Can someone tell me why the reinterpret_cast does not work?

Can someone tell me why the reinterpret_cast should not work?

AFAICS, the reinterpret_cast should work fine, but the assignment afterwards should cause an error.

That's because a const GOK_UINT8* is a non- const pointer to const GOK_UINT8 objects, while a const pGOK_UINT8 is a const pointer to non- const objects.
The former protects the object referred to, the latter the pointer referring to the object. If the assignment would be allowed, you could then change the object that the const GOK_UINT8* meant to protect from changing.


Note that typedef ed pointers behave strange that way. That's because of the strange declaration syntax of const in (C and thus also in) C++: A const protects the thing to its left, unless there isn't anything, then it protects the thing to its right. So in T const and in T const* , the object of type T is protected, while in T* const the pointer to an object of type T is protected. If you have

typedef T* TPtr;

then TPtr const again makes the pointer const . So does const TPtr . A typedef ed pointer either points to const or non- const objects, you can't change that. You can't stuff a const into the vicinity of TPtr and expect that to protect the objects the pointer refers to.

(BTW, this is why STL classes have to define both an iterator and a const_iterator .)

Yep sbi is correct.

Modified your code accordingly,

const char* c = "ret";
typedef unsigned char GOK_UINT8;
typedef const GOK_UINT8* pGOK_UINT8;
pGOK_UINT8 y = reinterpret_cast<const GOK_UINT8*>(c);
printf("%s", y);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM