Giter VIP home page Giter VIP logo

Comments (2)

pezy avatar pezy commented on August 19, 2024

第二行考虑到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 才是准确的.

from cppprimer.

SlothSimon avatar SlothSimon commented on August 19, 2024

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

from cppprimer.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.