reinterpret_cast或C型类型转换

reinterpret_cast or C Style type casting

本文关键字:类型转换 cast reinterpret      更新时间:2023-10-16

应该优先于reinterpret_cast而不是C样式的转换。请解释一下。

如果必须在 reinterpret_cast和 c 型铸造之间进行选择,应该首选哪一个

强制转换应该很少使用,而且要谨慎使用,如果你写:

char *x = const_cast<char *>(some_const_char_pointer_expression);

而不是用以下方式伪装它:

char *x = (char *)some_const_char_pointer_expression;

因此,请使用显式、受控、详细的表示法,因为它鼓励您避免强制转换,并在必须使用强制转换时使用正确、精确的强制转换。

C 样式的转换更通用。它从const_caststatic_castconst_cast static_castdynamic_cast中"选择",然后dynamic_cast const_cast,最后reinterpret_castreinterpret_cast const_cast。所以,如你所见,c-cast和reinterpret_cast之间有很大的区别,因为C-cast首先使用静态和动态cast。

如果你用C++写,你应该更喜欢上面的一个转换,而不是C样式的转换。它们更明确。但C型演员并不是非常非常糟糕的风格。