あなたがすべきstatic_cast
です。暗黙の変換を元に戻す場合に使用します。static_cast
ただし、この特定のケースでは、から変換しているため、違いはありませんvoid*
。しかし、一般的に、reinterpret_cast
2つのオブジェクトポインタ間のingは(§5.2.10/ 7)と定義されています。
オブジェクトポインタは、異なるタイプのオブジェクトポインタに明示的に変換できます。タイプ「pointerto」のprvaluev
がタイプ「 pointertocv 」T1
に変換されると、結果は、とが両方とも標準レイアウトタイプであり、の配置要件がのそれらよりも厳密でない場合、またはいずれかのタイプが。タイプ「pointerto」のprvalueをタイプ「pointerto 」(ここで、およびはオブジェクトタイプであり、の配置要件はの要件よりも厳密ではありません)に変換し、元のタイプに戻すと、元のポインタ値が生成されます。他のそのようなポインタ変換の結果は特定されていません。T2
static_cast<cv T2*>(static_cast<cv void*>(v))
T1
T2
T2
T1
void
T1
T2
T1
T2
T2
T1
強調鉱山。T1
あなたはすでにですので、 invoid*
へのキャストは何もしません。これは一般的に真実ではありません、それはドリュー・ドーマンが言っていることです:void*
reinterpret_cast
#include <iostream>
template <typename T>
void print_pointer(const volatile T* ptr)
{
// this is needed by oversight in the standard
std::cout << static_cast<void*>(const_cast<T*>(ptr)) << std::endl;
}
struct base_a {};
struct base_b {};
struct derived : base_a, base_b {};
int main()
{
derived d;
base_b* b = &d; // implicit cast
// undo implicit cast with static_cast
derived* x = static_cast<derived*>(b);
// reinterpret the value with reinterpret_cast
derived* y = reinterpret_cast<derived*>(b);
print_pointer(&d);
print_pointer(x);
print_pointer(y);
}
出力:
00CBFD5B
00CBFD5B
00CBFD5C
y
(実際にはを指していないためderived
、それを使用することは未定義の動作であることに注意してください。)
ここでreinterpret_cast
は、を通過するため、別の値を考え出しますvoid*
。static_cast
これが、可能な場合と必要な場合に使用する必要がある理由ですreinterpret_cast
。