为什么static_cast无法使用double void指针? [英] Why can't static_cast a double void pointer?

查看:110
本文介绍了为什么static_cast无法使用double void指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

上面的示例产生以下编译错误:

The above example produces the following compile error:

static_cast from 'void **' to 'int **' is not allowed

实时演示

我知道将void指针转换为任何其他指针类型的正确方法是使用static_cast.但是,不能static_cast将双void指针指向另一个其他类型的双指针.

I know that the proper way to cast a void pointer to any other pointer type is to use static_cast. However, you can't static_cast a double void pointer to another double pointer of other type.

  1. 为什么我们不能static_castvoid指针?
  2. 强制转换双void指针的正确方法是什么?
  1. Why we can't static_cast a double void pointer?
  2. What's the proper way to cast a double void pointer?

推荐答案

当您拥有void*并将其强制转换为int*时,可能会或可能不会进行一些数学/宽度调整来创建该对象的实例.正确的类型,将准备使用static_cast<>进行操作.当您只有一个指向void*的指针并且想要一个指向int*的指针时,static_cast<>对指向的void*对象没有写访问权限;因此,只有对void*的指针才能访问.不能随意调整它以确保它是有效的int*,以便static_cast<>可以成功并返回一个指针,该指针实际上可以用于访问有效的int*.在某些体系结构上,这可能并不重要,如果标准允许这样做,则移植时代码可能会中断. (请记住,期望static_cast<>为使用static_cast<int*>(the_void_ptr)进行初始化的int*安排一些额外的内存是不合理的-不仅会产生意外的开销,而且还需要将其存储在线程专用内存或动态分配并以某种方式释放,并且最终以指针值进行比较的所有形式的代码都将中断.)

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.)

如果您想强行解决问题,并向编译器保证这两种类型的宽度相同,并且不需要进行数学调整等.-您可以使用reinterpret_cast<>并对其进行调整,以使您清楚地知道承担不确定行为的风险.

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.

这篇关于为什么static_cast无法使用double void指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆