gpt4 book ai didi

c++ - 具有不同对齐要求的不同类型的两个对象可以具有相同的对象表示吗?

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:15 25 4
gpt4 key购买 nike

下面给出对象表示的定义(3.9/4):

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T).

但是 3.9.1/1 说:

A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.

看起来对象表示取决于对齐要求。但是我引用的定义中没有提到它。那是两个相同大小的对象可能具有不同的对象表示,是吗?

基本上,我问的是以下内容:假设我们有两个大小相同的对象,其中一个对象的对齐方式与另一个对象不同。例如:

struct A
{
char a;
char b;
char c;
char d;
};

A a; //Object 1. alignof(a) = 1
int b; //Object 2. alignof(b) = 4

这些对象是否具有相同的对象表示?

最佳答案

关于对齐的工作原理存在一些混淆。

你是对的,对象表示取决于对齐要求:

object representation is the sequence of sizeof(T) objects of type unsigned char

同时

The value representation of an object is the set of bits that hold the value of its type T

如果您采用以下类型:

struct S {
char c; // 1 byte value
// 3 bytes padding
float f; // 4 bytes value
bool operator==(const S& arg) const { // value-based equality
return c == arg.c && f == arg.f;
}
};
assert(sizeof(S) == 8); // object representation

对象表示大小占8个字节,而值表示大小只占5个字节,它决定了对象相对于另一个对象的值。存在导致差异的对齐要求,并且它们引入了一些填充。

在您的示例中,对象表示和值表示的类型具有相同的大小,加上对象表示大小等于值表示大小。

struct A
{
char a;
char b;
char c;
char d;
};

A a; //Object 1. Object representation size = 4, value representation size = 4, alignof(a) = 1
int b; //Object 2. Object representation size = 4, value representation size = 4, alignof(b) = 4

这里的不同之处在于存储和访问对象所需的对齐方式。

在某些处理器上访问非 4 字节对齐地址上的 4 字节整数会产生 fatal error 。您的代码段中使用的 alignof 关键字正是这样说的:您需要在 1 字节对齐的地址(即任何地方)上分配 A 类型的对象,因为您要访问子对象单个字节作为最大单次读取,它们可以安全地在任何地方访问,无论如何你需要在 4 字节对齐的地址上分配一个整数,以便我安全地访问它

§3.11/p1

Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated

这意味着:您应该在 4 字节对齐的地址上分配一个整数,但是从缓冲区开始到对象开始所需的字节不会成为对象的一部分:

|0x07|0x08|0x09|0x0A|0x0B|..
> I can allocate an integer here, on a 4-bytes-aligned address
> Here the buffer starts
|------------------|
object rep size == value rep size

请注意,如果不满足对齐要求会发生什么取决于系统,即在 x86 上你会遇到性能下降,使用 SSE 你可能会崩溃,在 GPU 内存空间上你将无法恢复你的程序。该标准仅规定了关于对齐分配请求应该发生的事情:

If a request for a specific extended alignment in a specific context is not supported by an implementation, the program is ill-formed. Additionally, a request for runtime allocation of dynamic storage for which the requested alignment cannot be honored shall be treated as an allocation failure.

关于c++ - 具有不同对齐要求的不同类型的两个对象可以具有相同的对象表示吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200639/

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