C++重新解释_cast
我不知道为什么这个简单的代码不起作用:
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;
}
有人可以告诉我为什么 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AFAICS,reinterpret_cast 应该可以正常工作,但是之后的赋值应该会导致错误。
这是因为
const GOK_UINT8*
是一个指向const
GOK_UINT8
对象的非const
指针,而const pGOK_UINT8
是指向非const
对象的const
指针。前者保护所引用的对象,后者保护引用该对象的指针。如果允许分配,您就可以更改 const GOK_UINT8* 旨在防止更改的对象。
请注意,
typedef
ed 指针的行为很奇怪。这是因为(C 以及 C++ 中的const
的声明语法很奇怪:Aconst
保护其左侧的内容,除非没有因此,在T const
和T const*
中,类型为T
受到保护,而在T* const
中,指向T
类型对象的指针受到保护。如果您有,则
TPtr const
再次使指针const
。 const TPtr 也是如此。typedef
ed 指针要么指向const
对象,要么指向非const
对象,您无法更改它。您不能将const
填充到TPtr
附近并期望它能够保护指针引用的对象。(顺便说一句,这就是为什么 STL 类必须同时定义迭代器和 const_iterator。)
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 toconst
GOK_UINT8
objects, while aconst pGOK_UINT8
is aconst
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 ofconst
in (C and thus also in) C++: Aconst
protects the thing to its left, unless there isn't anything, then it protects the thing to its right. So inT const
and inT const*
, the object of typeT
is protected, while inT* const
the pointer to an object of typeT
is protected. If you havethen
TPtr const
again makes the pointerconst
. So doesconst TPtr
. Atypedef
ed pointer either points toconst
or non-const
objects, you can't change that. You can't stuff aconst
into the vicinity ofTPtr
and expect that to protect the objects the pointer refers to.(BTW, this is why STL classes have to define both an
iterator
and aconst_iterator
.)是的,sbi 是正确的。
相应地修改了您的代码,
Yep sbi is correct.
Modified your code accordingly,