gpt4 book ai didi

c++ - 使用 static_cast 将任何指针转换到 char 指针

转载 作者:太空狗 更新时间:2023-10-29 21:19:42 24 4
gpt4 key购买 nike

如果根据严格的别名规则,char 指针可以指向任何类型的指针,那么为什么我不能使用 static_cast 将任何类型的指针转​​换为 char 指针?

char *ptr;
int *intPtr;

ptr = reinterpret_cast<char*>(intPtr); // ok
ptr = static_cast<char*>(intPtr); // error: invalid static_cast from type 'int*' to type 'char*'

最佳答案

static_cast 的工作原理与严格的别名规则无关。

static_cast 不允许您在任意指针类型之间进行转换,它只能用于转换为 1 和 from2 void*(转换为 void* 通常是多余的,因为转换已经是隐式的3)。

你可以这样做

ptr = static_cast<char*>(static_cast<void*>(intPtr));

但是那和

绝对没有区别 4
ptr = reinterpret_cast<char*>(intPtr);

https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf

1[expr.static.cast]/6

2[expr.static.cast]/13

3[conv.ptr]/2

4[expr.reinterpret.cast]/7

关于c++ - 使用 static_cast 将任何指针转换到 char 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502169/

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