gpt4 book ai didi

c++ - 为什么我可以将 void* static_cast 转换为 int* 但不能转换为 int*&?

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:58 25 4
gpt4 key购买 nike

API 使用void* 来存储未类型化的指针偏移量。这有点老套,但没关系。

为了表达我的偏移算法,我尝试做这样的事情

int main ()
{
void * foo;

foo = static_cast <int *> (nullptr) + 100;

static_cast <int * &> (foo) += 100;
}

最后一行编译失败(gcc)

x.cpp:7:28: error: invalid static_cast from type ‘void*’ to type ‘int*&’

修复很简单:

foo = static_cast <int *> (foo) + 100;

但为什么不允许第一个呢?

在您回答“因为标准这么说”之前,为什么标准这么说?第一种方法有什么危险吗?或者这只是一个疏忽?

最佳答案

出于与int i; static_cast<long &>(l) = 3L; 相同的原因,不允许这样做不允许。

当然,在很多实现中(intlong 具有相同的大小、表示和对齐方式),它可以工作。但是强制转换有效的规则对于所有实现都是基本相同的,显然这在 int 的平台上永远行不通。和 long具有不同的大小,这意味着不可能允许在这些平台上访问一个作为另一个。

从历史上看,有实现 void *int *有不同的表示。

后来,在标准声明访问 void * 之后就好像它是一个 int *是无效的,实现也开始基于有效程序不这样做的假设进行优化:

void *f (void **ppv, int **ppi) {
void *result = *ppv;
*ppi = nullptr;
return result;
}

允许实现对此进行优化

void *f (void **ppv, int **ppi) {
*ppi = nullptr;
return *ppv;
}

而这样的优化,当它们减少代码大小或提高效率时,如今已司空见惯。如果f被允许称为 void *pv = &pv; f (pv, &static_cast<int*&>(pv)); ,此优化将无效。因为这种优化已被证明是有用的,所以规则不太可能改变。

关于c++ - 为什么我可以将 void* static_cast 转换为 int* 但不能转换为 int*&?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com