Is listing float * legal for std :: complex <float> * is legal

N3797 26.4 [complex.numbers] speaks about the ebb of std::complex<T>* to T*

4 In addition, if a is an expression of the type cv std::complex<T>* , and the expression a[i] correctly defined for the integer expression i , then: - reinterpret_cast<cv T*>(a)[2*i] should denote the real part a[i] and
- reinterpret_cast<cv T*>(a)[2*i + 1] denotes the imaginary part of a[i] .

Does this (or some other wording of the standard) mean that I can reinterpret_cast another way? Can i do this:

  float * pf; std::complex<float>* pc = reinterpret_cast<std::complex<float>*>(pf); pc[i].real(); 

As nm below, I had to make sure that the pf alignment is suitable for a std::complex<float> . This can be taken care of.

+7
c ++ language-lawyer c ++ 11
source share
2 answers

No, this clause does not provide such a guarantee.

Now in practice, alignment will be the most common problem: but even this can be rare.

The second problem is associated with a strict alias, where the memory allocated as double can be accepted by the compiler so that it is not modified by any operation with pointers to other types (except char ). The above position restricts movement in another way (the complex pointer, which thay double* cannot accept, does not indicate its data), but not in the direction you want. Again, this is relatively obscure, but the compiler can use this to reorder the entries in your code.

However, it will work. Most often, if you align it, and your compiler does not use the strict assumptions of aliases: even then this behavior is undefined by standard.
+3
source share

This does not work the other way around. A std::complex<float> is two consecutive float in memory, which is confirmed by what the standard allows, but you have a pointer to a single float value and turn it into a pointer to a structure that should contain two floats. Even if you have two floats, the standard does not guarantee this, and therefore it would be unlawful to reinterpret_cast pointers in that direction.

+1
source share

All Articles