Reinterpret_cast use in C++
Just a simple question,having this:
fftw_complex *H_cast;
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_comp开发者_运维知识库lex)*M*N);
what is the difference between:
H_cast= reinterpret_cast<fftw_complex*> (H);
and
H_cast= reinterpret_cast<fftw_complex*> (&H);
Thanks so much in advance
Antonio
Answer to current question
The difference is that they do two completely different things!
Note: you do not tell us what H
is, so it's impossible to answer the question with confidence. But general principles apply.
For the first case to be sensible code, H
should be a pointer (typed as void*
possibly?) to a fftw_complex
instance. You would do this to tell the compiler that H
is really a fftw_complex*
, so you can then use it.
For the second case to be sensible code, H
should be an instance of a class with a memory layout identical to that of class fftw_complex
. I can't think of a compelling reason to put yourself in this situation, it is very unnatural. Based on this, and since you don't give us information regarding H
, I think it's almost certainly a bug.
Original answer
The main difference is that in the second case you can search your source code for reinterpret_cast
(and hopefully ensure that every use is clearly documented and a necessary evil).
However, if you are casting from void*
to another pointer type (is this the case here?) then it's preferable to use static_cast
instead (which can also be easily searched for).
H_cast= reinterpret_cast<fftw_complex*> (H);
This converts the pointer-ish type inside H (or the integer itself, if H is an integer type) and tells the compiler "this is a pointer. Stop thinking whatever it was, it's a pointer now". H is used as something where you had stored a pointer-like address.
H_cast= reinterpret_cast<fftw_complex*> (&H);
This converts the address of H (which is a pointer to whatever type H is) into a pointer to "fftw_complex". Modifying the contents of H_cast will now change H itself.
You'll want the second if H is not a pointer and usually the first if it is. There are use cases for the other way around but they're uncommon and ugly (especially reinterpreting an int or - god forbid - a double as a pointer).
Pointer casts are always executed as a reinterpret_cast, so when casting from or to a void * there's no difference between a c-style cast, a static_cast or a reinterpret_cast.
Reinterpret_casts are usually reserved for the ugliest of locations where c-style casts and static_casts are used for innocuous casts. You basically use reinterpret_cast to tag some code as really-ugly:
float f = 3.1415f;
int x = *reinterpret_cast<int *>(&f);
That way, these ugly unsafe casts are searchable/greppable.
精彩评论