相关疑难解决方法(0)

具有单个元素的struct的大小

特定

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)

或者它可能依赖于实现?

c c++

18
推荐指数
2
解决办法
1751
查看次数

常见的初始序列和对齐

在考虑这个问题的反例时,我提出了:

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)

c++ memory-alignment unions standard-layout c++11

13
推荐指数
1
解决办法
916
查看次数

UB解引用联合数组时

以下哪些是不确定的行为:

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)

c++ undefined-behavior

1
推荐指数
1
解决办法
214
查看次数