问题描述
这是一个严格走样的问题,如将编译器造成任何优化订单的问题与此有关。
说我在结构XMFLOAT3
(不同于浮动取值href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xmfloat3%28v=vs.85%29.aspx\"相对=nofollow>这个。)我想转换为浮法*
。这将降落在我的优化麻烦吗?
XMFLOAT3富= {1.0F,2.0F,3.0F};
自动栏=安培; foo.x;酒吧[2] + = 5.0F;
foo.z + = 5.0F;
COUT<< foo.z;
我相信这将始终打印13。但是这个code:
XMFLOAT3富= {1.0F,2.0F,3.0F};
自动栏= reinter pret_cast<浮动*>(安培;富);酒吧[2] + = 5.0F;
foo.z + = 5.0F;
COUT<< foo.z;
我相信这是合法的,因为根据的
Is my understanding of this correct?
The reinterpret_cast
from XMFLOAT3*
to float*
is OK, due to:
9.2 [class.mem] paragraph 20:
That means the address of the first member is the address of the struct, and there's no aliasing involved when you access *bar
because you're accessing a float
through an lvalue of type float
, which is fine.
But the cast is also unnecessary, it's equivalent to the first version:
auto bar = &foo.x;
The expression bar[2]
is only OK if there is no padding between the members of the struct, or more precisely, if the layout of the data members is the same as an array float[3]
, in which case 3.9.2 [basic.compound] paragraph 3 says it is OK:
In practice there is no reason that three adjacent non-static data members of the same type would not be laid out identically to an array (and I think the Itanium ABI guarantees it), but to be safe you could add:
static_assert(sizeof(XMFLOAT3)==sizeof(float[3]),
"XMFLOAT3 layout must be compatible with float[3]");
Or to be paranoid, or if there are just additional members after z
:
static_assert(offsetof(XMFLOAT3, y)==sizeof(float)
&& offsetof(XMFLOAT3, z)==sizeof(float)*2,
"XMFLOAT3 layout must be compatible with float[3]");
Yes, it relies on it being a standard-layout class type, and on the order and type of its data members.
这篇关于铸造的Struct到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!