特定
struct S {
SomeType single_element_in_the_struct;
};
Run Code Online (Sandbox Code Playgroud)
这总是如此
sizeof(struct S) == sizeof(SomeType)
Run Code Online (Sandbox Code Playgroud)
或者它可能依赖于实现?
在考虑这个问题的反例时,我提出了:
struct A
{
alignas(2) char byte;
};
Run Code Online (Sandbox Code Playgroud)
但如果这是合法的和标准的布局,它是否与布局兼容struct B?
struct B
{
char byte;
};
Run Code Online (Sandbox Code Playgroud)
此外,如果我们有
struct A
{
alignas(2) char x;
alignas(4) char y;
};
// possible alignment, - is padding
// 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
// x - - - y - - - x - - - y - - -
struct B
{
char x;
char y;
}; // …Run Code Online (Sandbox Code Playgroud) 以下哪些是不确定的行为:
template <class T> struct Struct { T t; };
template <class T> union Union { T t; };
template <class T> void function() {
Struct aS[10];
Union aU[10];
// do something with aS[9].t and aU[9].t including initialization
T *aSP = reinterpret_cast<T *>(aS);
T *aUP = reinterpret_cast<T *>(aU);
// so here is this undefined behaviour?
T valueS = aSP[9];
// use valueS in whatever way
// so here is this undefined behaviour?
T valueU = aUP[9];
// use valueU in …Run Code Online (Sandbox Code Playgroud)