Why can't static_cast a double void pointer?

后端 未结 5 1345
忘掉有多难
忘掉有多难 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 06:42

    void* is special in that it can point to anything. It is a "pointer to unspecified type." Therefore, converting to and from void* to T* for some type T is a "normal" operation, one which static_cast can support. In effect, such a conversion says: "The pointer doesn't know to what it points, but I know it: it points to a T."

    void** is not special special in this way. It can point to one thing only, to a void*. Converting a void** to an int** says something different: "The pointer claims it points to a void*, but I want to treat it as a pointer to int* instead." And if you want to treat one thing as a different thing, you want to reinterpret the original - so use reinterpret_cast.

提交回复
热议问题