reinterpret_cast(char*) 与 static_cast(static_cast(char*)) -- 使用哪个?
当您动态分配 char *
类型的缓冲区并希望将其转换为特定类型时,您应该使用类似的东西
reinterpret_cast<int *>(char *)
还是类似的东西
static_cast<int *>(static_cast<void *>(char *))
,为什么?
我个人倾向于使用后者,因为对我来说,它并不是真正的数据“重新解释”(而只是分配缓冲区的机械方式),而且看起来它不会成为错误的来源与典型的reinterpret_cast
可能是相同的方式,但这是正确的直觉吗?
When you've dynamically allocated a buffer of type char *
and want to cast it to a particular type, should you use something like
reinterpret_cast<int *>(char *)
or something like
static_cast<int *>(static_cast<void *>(char *))
and why?
I'm personally tempted to use the latter, because to me, it's not really a "reinterpretation" of the data (rather just a mechanical way of allocating the buffer) and it doesn't look like it would be a source of bugs in the same way as a typical reinterpret_cast
might be, but is this the correct intuition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Dave Abrahams,使用链式
static_cast< /code>s 是强制指针类型的正确、标准方法。
就我个人而言,我在这些情况下使用
reinterpret_cast
,因为我从来不需要处理那些用链式static_cast
做一件事而用单个做不同事情的架构。 reinterpret_cast
。According to Dave Abrahams, using the chained
static_cast
s is the correct, standard way to coerce pointer types.Personally, I use
reinterpret_cast
in these cases because I never have to deal with architectures that would do one thing with the chainedstatic_cast
s and a different thing with the singlereinterpret_cast
.