gpt4 book ai didi

c++ - sizeof(T) == sizeof(int) 吗?

转载 作者:IT老高 更新时间:2023-10-28 23:18:24 25 4
gpt4 key购买 nike

我一直在研究标准草案,但似乎找不到我想要的东西。

如果我有标准布局类型

struct T {
unsigned handle;
};

那我知道reinterpret_cast<unsigned*>(&t) == &t.handle对于一些 T t;

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

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

this question解决了一个非常相似的主题,我问的是数据成员和类都是标准布局的具体情况,并且数据成员是基本类型。

我读过一些段落,似乎暗示也许这可能是真的,但没有什么能击中头的。例如:

第 9.2.17 节

Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types

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

最佳答案

你基本上是在问,给定:

struct T {
U handle;
};

是否保证sizeof(T) == sizeof(U).不,不是。

ISO C++03 标准的第 9.2/17 节说:

A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

假设您有一个 struct T 数组。反之亦然部分意味着任何 T::handle 成员的地址也必须是 struct T 的有效地址。现在,假设这些成员的类型是 char 并且您的声明是正确的。这意味着 struct T 将被允许具有未对齐的地址,这似乎不太可能。该标准通常试图不以这种方式束缚实现的双手。为了使您的声明属实,该标准必须要求允许 struct T 具有未对齐的地址。所有结构都必须允许它,因为 struct T 可以是前向声明的不透明类型。

此外,第 9.2/17 节继续说明:

[Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment.]

换一种说法,这意味着不能保证永远不会有填充。

关于c++ - sizeof(T) == sizeof(int) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com