简体   繁体   中英

reinterpret_cast<int*>(char*) vs. static_cast<int*>(static_cast<void*>(char*)) — which to use?

When you've dynamically allocated a buffer of type char * and want to cast it to a particular type, should you use something like

reinterpret_cast<int *>(char *)

or something like

static_cast<int *>(static_cast<void *>(char *))

and why?

I'm personally tempted to use the latter, because to me, it's not really a "reinterpretation" of the data (rather just a mechanical way of allocating the buffer) and it doesn't look like it would be a source of bugs in the same way as a typical reinterpret_cast might be, but is this the correct intuition?

According to Dave Abrahams , using the chained static_cast s is the correct, standard way to coerce pointer types.

Personally, I use reinterpret_cast in these cases because I never have to deal with architectures that would do one thing with the chained static_cast s and a different thing with the single reinterpret_cast .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM