Why can't static_cast a double void pointer?

后端 未结 5 1347
忘掉有多难
忘掉有多难 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:08

    When you have a void* and cast it to an int*, there may or may not be some mathematical/width adjustment to create an instance of the proper type, which static_cast<> will be prepared to do. When you have only a pointer to a void* and want a pointer to an int*, the static_cast<> has no write access to the pointed-to void* object; it is not free to adjust it to make sure it's a valid int* such that the static_cast<> can succeed and return a pointer which really can be used to access a valid int*. While on some architectures this may not matter, if the standard allowed this then the code could break when ported. (Keep in mind that it's unreasonable to expect the static_cast<> to arrange for some additional memory for an int* somewhere that it initialises using a static_cast(the_void_ptr) - not only would that have unexpected overheads, but it'd need to be in thread specific memory or allocated dynamically and released somehow, and all manner of code that actually ends up comparing the pointer values would break.)

    If you want to force the matter and promise the compiler that the width of both types is the same and no mathematical adjustment is necessary etc. - then you can use reinterpret_cast<> and boss it around, making it clear you're accepting the risk of undefined behaviour.

提交回复
热议问题