微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – UnsafeRawPointer assumeMemoryBound vs. bindMemory

任何人都可以解释UnsafeRawPointer.assumimgMemoryBound(to :)和UnsafeRawPointer.bindMemory(to:capacity :)之间有什么区别?

编译或运行时差的一个实际例子将更受欢迎.

Swift Doc说关于bindMemory(to:capacity :):

This API allows a region of memory to hold unrelated types at different points in the program. Binding uninitialized memory to a type prepares the memory to store values of that type. Binding memory that is already initialized reinterprets the in-memory values as the new type. If the old values are either nontrivial (require destruction) or if they are ever read from memory before being overwritten,then the new type must be mutually layout compatible with the old type.

是什么意思将未初始化的内存绑定到一个类型准备内存来存储该类型的值?它分配了字节,对吧?那么bindMemory(to:capacity :)完成后有什么不同?

Swift中分配的内存可以是:

>未初始化的原始内存
>未初始化的内存绑定到一个类型
>初始化的内存绑定到一个类型

当您使用UnsafeMutableRawPointer.allocate(bytes:alignedTo :)分配内存时,您将获得未初始化的原始内存.

当您使用UnsafeMutablePointer< T> .allocate(capacity :)分配内存时,您将获得与T类型绑定的未初始化内存.

> bindMemory(to:capacity:)(重新)将指针的内存绑定到一个新类型,并返回一个类型指针来访问它.它可以在任何上述状态的指向内存的指针上调用;虽然如果内存初始化,新绑定类型必须与旧绑定类型布局兼容,并且两种类型都应为trivial.

请注意,此方法不执行分配或初始化;它只是改变了内存的绑定类型.
> assumingMemoryBound(to:)是一种从已知的原始指针获取类型指针的方法,该指针指向绑定到给定类型的内存.如果内存未绑定到此类型,则通过您返回的类型指针访问内存是未定义的行为.

这里要注意的一件重要事情是内存只能在给定时间绑定到一种类型.您可以自由重新绑定到其他类型(具有上述初始化内存的限制);但是,尝试访问绑定到给定类型的内存作为无关类型会违反严格别名,因此是未定义的行为.

另外需要注意的是,相关类型和布局兼容类型是独立的概念:

>类型T是与类型U兼容的布局,如果绑定到类型U的存储器可以按位重新解释为具有类型T.注意,这不一定是双向关系.例如,如果(Int,Int)的一个“实例”可以被重新解释为2 x Int,则Int与布局兼容(Int,Int).反过来说不可能是真的;您不能从单个Int形成(Int,Int)值.
>如果您可以将重叠内存与这些类型别名,则两种类型相关.例如,如果您有UnsafePointer< T>和UnsafePointer< U>,如果T和U是不相关的类型,则它们不能指向彼此重叠的存储器.

但是,我不相信Swift已经正式定义了这些术语的任何规则(我希望这将伴随ABI稳定性).

So what’s different after bindMemory(to:capacity:) completes?

目前,没什么.作为Andrew Trick says邮件列表中讨论Martin linked to

Binding memory communicates to the compiler that the memory locations are safe for typed access. nothing happens at runtime–until someone writes a type safety sanitizer. It affects the abstract state of the memory location,independent of the pointer variable used to access that memory. Binding memory returns a typed pointer for convenience and clarity,but there’s nothing special about that particular pointer value.

有关此主题的进一步阅读,请参阅memory model explanation section of SE-0107以及此unofficial guide to strict aliasing in Swift.

原文地址:https://www.jb51.cc/swift/319116.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐