问题描述
根据, reinter pret_cast
:
But wait, that's a lie cause it only works in these cases:
According to that list an illegal example would be:
auto foo = 13LL;
auto bar = reinterpret_cast<double&>(foo);
So the only acceptable way to make that cast is to copy the memory:
auto foo = 13LL;
double bar;
copy_n(reinterpret_cast<char*>(&foo), sizeof(foo), reinterpret_cast<char*>(&bar));
My question is, why doesn't reinterpret_cast
handle that for me? Or is there something else available so I don't have to jump through this hoop?
One reason is that the size, alignment, and bit representations aren't specified, so such a conversion wouldn't be portable. However, that wouldn't really justify making the behaviour undefined, just implementation-defined.
By making it undefined, the compiler is allowed to assume that expressions of unrelated types don't access the same object, which can allow better optimisation. For example, in the following:
int & i = something();
float & f = something_else();
const int i1 = i;
f = 42;
const int i2 = i;
the compiler can assume that i1
and i2
both have the same value (i
being unchanged by the assignment to f
), and optimise them into a single constant. Breaking the assumption will then cause undefined behaviour.
Copying the bytes is the only well-defined way to reinterpret one object type as an unrelated type.
Aliasing with reinterpret_cast
or a union might work sometimes (assuming the size etc. match), but might trip you up if the optimiser gets too clever with undefined behaviour.
这篇关于为什么不reinter尺寸相同类型的pret_cast力copy_n的强制类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!