相关疑难解决方法(0)

使用联合在具有共同初始序列的两个结构之间进行转换是否合法且定义良好的行为(参见示例)?

我有一个公开面向结构A和内部结构B的API,需要能够将结构B转换为结构A.以下代码在C99(和VS 2010/C89)和C中是合法且定义良好的行为 ++ 03/C++ 11?如果是,请解释是什么使它明确定义.如果不是,那么在两种结构之间进行转换的最有效和跨平台的方法是什么?

struct A {
  uint32_t x;
  uint32_t y;
  uint32_t z;
};

struct B {
  uint32_t x;
  uint32_t y;
  uint32_t z;
  uint64_t c;
};

union U {
  struct A a;
  struct B b;
};

int main(int argc, char* argv[]) {
  U u;
  u.b.x = 1;
  u.b.y = 2;
  u.b.z = 3;
  u.b.c = 64;

  /* Is it legal and well defined behavior when accessing the non-write member of a union in this case? */
  DoSomething(u.a.x, u.a.y, …
Run Code Online (Sandbox Code Playgroud)

c c++ c99 c89 unions

16
推荐指数
2
解决办法
681
查看次数

sizeof(T)== sizeof(int)?

我一直在研究草案标准,似乎无法找到我正在寻找的东西.

如果我有标准布局类型

struct T {
   unsigned handle;
};
Run Code Online (Sandbox Code Playgroud)

然后我知道reinterpret_cast<unsigned*>(&t) == &t.handle对某些人T t;

目标是创建一些vector<T> v并传递&v[0]给一个C函数,该函数需要一个指向无符号整数数组的指针.

那么,标准是否定义sizeof(T) == sizeof(unsigned)并且这是否意味着数组T将具有与数组相同的布局unsigned

虽然这个问题涉及一个非常相似的主题,但我要问的是数据成员和类都是标准布局的特定情况,而数据成员是基本类型.

我读过一些段落,似乎暗示,也许它可能是真的,但没有什么击中了要害.例如:

§9.2.17

两个标准布局结构(第9节)类型是布局兼容的,如果它们具有相同数量的非静态数据成员,并且相应的非静态数据成员(按声明顺序)具有布局兼容类型

这不是我想要的,我不认为.

c++ arrays sizeof

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

标签 统计

c++ ×2

arrays ×1

c ×1

c89 ×1

c99 ×1

sizeof ×1

unions ×1