开发者

C++ reinterpret_cast

I don't kno开发者_开发知识库w 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 typedefed 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 typedefed 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜