两个指针之间的转换/转换
最近我做了很多关于文件流的练习。当我使用 fstream.write(...) 时 例如,编写一个包含 10 个整数的数组 (intArr[10]
),我会这样写:
fstream.write((char*)intArr,sizeof(int)*10);
(char*)intArr
强制转换安全吗?直到现在我才遇到任何问题,但我了解了 static_cast
(c++ 方式对吗?)并使用了 static_cast
和它失败的!我无法理解......我应该改变我的方法吗?
Lately I've been doing a lot of exercises with file streams. When I use fstream.write(...)
to e.g. write an array of 10 integers (intArr[10]
) I write:
fstream.write((char*)intArr,sizeof(int)*10);
Is the (char*)intArr
-cast safe? I didn't have any problems with it until now but I learned about static_cast
(the c++ way right?) and used static_cast<char*>(intArr)
and it failed! Which I cannot understand ... Should I change my methodology?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态转换根本不是正确的事情。仅当相关类型自然可转换时,才能执行静态转换。但是,不相关的指针类型不能隐式转换;即,
T*
通常不能与U*
相互转换。您真正要做的是重新解释强制转换:在 C++ 中,C 样式强制转换
(char *)
成为最合适的可用转换类型,其中最弱的是重新诠释的演员阵容。使用显式 C++ 样式转换的好处是可以证明您了解所需的转换类型。 (此外,没有与const_cast
等价的 C 语言。)也许注意到这些差异是有启发性的:
题外话:编写最后一行的正确方法有点复杂,但使用了大量的量铸造:
A static cast simply isn't the right thing. You can only perform a static cast when the types in question are naturally convertible. However, unrelated pointer types are not implicitly convertible; i.e.
T*
is not convertible to or fromU*
in general. What you are really doing is a reinterpreting cast:In C++, the C-style cast
(char *)
becomes the most appropriate sort of conversion available, the weakest of which is the reinterpreting cast. The benefit of using the explicit C++-style casts is that you demonstrate that you understand the sort of conversion that you want. (Also, there's no C-equivalent to aconst_cast
.)Maybe it's instructive to note the differences:
Off-topic: The correct way of writing the last line is a bit more involved, but uses copious amounts of casting: