I am converting a bunch of code to use C ++ style styles (using -Wold-style-cast ). I do not completely sell its use for primitive variables, but I am new to C ++ style in general.
One problem arises in endian coding code. The current code looks like this:
#define REINTERPRET_VARIABLE(VAR,TYPE) (*((TYPE*)(&VAR)))
Now, endianness does not care about subscription. Therefore, to reverse int16_t , we can treat it exactly like a uint16_t for reversal purposes. This offers the following code:
int16_t reverse( int16_t val) { return reinterpret_cast<int16_t>(reverse(reinterpret_cast<uint16_t>(val))); }
However, as described in this and, in particular, this question, reinterpret_cast requires a link or a pointer (if it does not throw itself at it). This allows:
int16_t reverse( int16_t val) { return reinterpret_cast<int16_t&>(reverse(reinterpret_cast<uint16_t&>(val))); }
This does not work because, as my compiler says, an external cast requires an lvalue. To fix this, you need to do something like:
int16_t reverse( int16_t val) { uint16_t temp = reverse(reinterpret_cast<uint16_t&>(val)); return reinterpret_cast<int16_t&>(temp); }
This is not much different from the source code, and indeed, the temporary variable exists for the same reason, but four questions were raised for me:
- Why temporary, even necessary for
reinterpret_cast ? I can understand that a mute compiler should have a temporary approach to support the muck of the REINTERPRET_VARIABLE pointer, but reinterpret_cast should just reinterpret the bit. Is it related to RVO or something? - Would it require a temporary refund to be related to performance, or maybe the compiler can understand that a temporary refund should really only be a return value?
- The second
reinterpret_cast looks like a return link. Since the return value of the function is not a reference, I am sure that everything is in order; the return value will be a copy, not a link. However, I still would like to know what link casting really even means? This is appropriate in this case, right? - Are there any other performance implications I should be aware of? I would suggest that
reinterpret_cast would be, if at all possible, faster since the compiler does not need to figure out that the bits should be reinterpreted - am I just saying that they should?
source share