101*_*010 6 c++ pointers void-pointers
考虑以下代码:
void **v_dptr(nullptr);
int **i_dptr = static_cast<int**>(v_dptr);
Run Code Online (Sandbox Code Playgroud)
上面的示例产生以下编译错误:
static_cast from 'void **' to 'int **' is not allowed
我知道将void指针强制转换为任何其他指针类型的正确方法是使用static_cast.但是,您不能static_cast将void指针指向其他类型的另一个双指针.
static_cast双void指针?void指针的正确方法?Ton*_*roy 12
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<int*>(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.
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.
| 归档时间: |
|
| 查看次数: |
2162 次 |
| 最近记录: |