Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exercise 4.37 疑问 #67

Closed
SlothSimon opened this issue Aug 2, 2016 · 2 comments
Closed

exercise 4.37 疑问 #67

SlothSimon opened this issue Aug 2, 2016 · 2 comments

Comments

@SlothSimon
Copy link

SlothSimon commented Aug 2, 2016

给出的答案如下:

int i; double d; const string *ps; char *pc; void *pv;
pv = (void*)ps; // pv = const_cast<string*>(ps); or pv = static_cast<void*>(const_cast<string*>(ps));
i = int(*pc);   // i = static_cast<int>(*pc);
pv = &d;        // pv = static_cast<void*>(&d);
pc = (char*)pv; // pc = reinterpret_cast<char*>(pv);

但自己看书理解后做题,第二行考虑到_pc和i一个是char一个是int,和reinterpret_cast部分的例子差不多,感觉应该用reinterpret_cast。
而第四行考虑到是从pv的void_类型变到pc的char*类型,和static_cast给的第二个例子一样,感觉应该用static_cast。
不知道我理解上是否有误?

@pezy
Copy link
Owner

pezy commented Aug 4, 2016

第二行考虑到pc和i一个是char一个是int,和reinterpret_cast部分的例子差不多,感觉应该用reinterpret_cast。

你说的例子是:

int *ip;
char *pc = reinterpret_cast<char*>(ip);

吗?

如果是, 那可完全不一样, 例子里, 是从 int* to char*, 这是地址层面的转换, 且使用不当, 会造成运行时错误.(书上针对这个例子, 就紧接着一个错误案例)

i = int(*pc);

第二行这个, 是 char to int, 就是基本类型转换而已. 甚至你不写这个 int() 也没事, 会自动提升. 所以应该使用 static_cast.

你看, 这完全不是一回事.


而第四行考虑到是从pv的void类型变到pc的char*类型,和static_cast给的第二个例子一样,感觉应该用static_cast。

先看你提到的第二个例子:

void* p = &d; // ok: address of any nonconst object can be stored in a void*
// ok: converts void* back to the original pointer type
double *dp = static_cast<double*>(p);

注意下文提及的一句话:

use a static_castto cast the pointer back to its original type

所以可以推测, d 是个 double 类型的变量, 我们暂时将其地址转为 void*(可能为了适应调用接口, 可能为了网络传输), 然后通过 static_cast 再转为 double*, 从而正确取值.

也就是说, static_cast 在这里是一种 还原.

那么, 再回到咱们的问题, 第四行里, pv 是什么? 从命名看, 完全看不出其原来指向的是什么类型, v 似乎仅仅只是 void 的缩写. 那么我们将其转为 char*, 实际是一种冒风险的强制转换. 而并不是上面例子里的还原. 针对地址层面的强制转换, 用 reinterpret_cast 才是准确的.

@SlothSimon
Copy link
Author

感结合说明又反复看了几遍例子,终于弄懂了!弄懂了后感觉问的问题好小白⋯⋯谢谢大神这么耐心的解释!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants