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?
AFAICS, the
reinterpret_castshould work fine, but the assignment afterwards should cause an error.That’s because a
const GOK_UINT8*is a non-constpointer toconstGOK_UINT8objects, while aconst pGOK_UINT8is aconstpointer to non-constobjects.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 ofconstin (C and thus also in) C++: Aconstprotects the thing to its left, unless there isn’t anything, then it protects the thing to its right. So inT constand inT const*, the object of typeTis protected, while inT* constthe pointer to an object of typeTis protected. If you havethen
TPtr constagain makes the pointerconst. So doesconst TPtr. Atypedefed pointer either points toconstor non-constobjects, you can’t change that. You can’t stuff aconstinto the vicinity ofTPtrand expect that to protect the objects the pointer refers to.(BTW, this is why STL classes have to define both an
iteratorand aconst_iterator.)