Why can't static_cast a double void pointer?

后端 未结 5 1380
忘掉有多难
忘掉有多难 2021-01-12 06:05

Consider the following piece of code:

void **v_dptr(nullptr);
int  **i_dptr = static_cast(v_dptr);

The above example produces

5条回答
  •  爱一瞬间的悲伤
    2021-01-12 07:07

    A static_cast can do the reverse of any implicit conversion.

    There is an implicit conversion int*void*; it doesn't do more than lose the information about the type of the pointed to object.

    There is no implicit conversion int**void**. If it was allowed it would reinterpret the object pointer to, namely, reinterpreting an int* as a void*. On some old architectures an int* did not necessarily have as large a value representation as a void* (or char*, the pointer types with the least alignment requirements).

    The reinterpretation requires a reinterpret_cast.

    IMHO it's a good idea to use reinterpret_cast in general for conversions to/from void*, because that communicates intent to the reader. However, as I recall Sutter and Alexandrescu recommended using static_cast, presumably due to a lack of a formal guarantee in C++03. Also as I recall, that purely formal problem was fixed in C++11.

提交回复
热议问题