Swift 是否保证类和结构中字段的存储顺序? [英] Does Swift guarantee the storage order of fields in classes and structs?

查看:24
本文介绍了Swift 是否保证类和结构中字段的存储顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,您在结构中定义字段的顺序就是它们在内存中实例化的顺序.考虑到内存对齐,如图所示,以下结构体在内存中的大小为 8 个字节,但如果字段颠倒,则只有 6 个字节,因为不需要任何对齐填充.

In C, the order in which you define fields in a struct is the order in which they will be instantiated in memory. Taking into account memory alignment, the following struct will have a size of 8 bytes in memory as shown, but only 6 bytes if the fields are reversed as there doesn't need to be any alignment padding.

struct s {
    int32_t a;
    /* 2 bytes of padding to align a 64 bit integer */
    int64_t b;
}

这种顺序保证存在于 C 结构、C++ 类(和结构)和 Objective-C 类中.

This ordering guarantee is present in C structs, C++ classes (and structs), and Objective-C classes.

Swift 类和结构体中的字段的存储顺序是否同样得到保证?或者(鉴于该语言不支持与其他语言相同的指针),编译器是否会在编译时以最佳方式为您重新排列它们?

Is the order of storage similarly guaranteed for fields in Swift classes and structs? Or (given that the language doesn't support pointers in the same way as the others listed), does the compiler optimally re-arrange them for you at compile-time?

推荐答案

是的,struct元素在内存中的顺序就是他们的声明.详情可见在 类型布局(强调).但是请注意当前"的使用,所以这个在 Swift 的未来版本中可能会发生变化:

Yes, the order of the struct elements in memory is the order of their declaration. The details can be found in Type Layout (emphasis added). Note however the use of "currently", so this may change in a future version of Swift:

脆弱的结构和元组布局

结构和元组目前共享相同的布局算法,在编译器实现中被称为通用"布局算法.算法如下:

Structs and tuples currently share the same layout algorithm, noted as the "Universal" layout algorithm in the compiler implementation. The algorithm is as follows:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆