Search code examples
c++fftwreinterpret-cast

Reinterpret_cast use in C++


Just a simple question,having this:

fftw_complex *H_cast;
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*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


Solution

  • 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).