以下是我的猜测,请有经验的人指出我理解不正确的部分。
如果我有一个类,它的实例占用128位,叫做
首先,我调用
如果我调用
但是如果我调用
然后任何访问都是安全的。然而这并不能解释为什么
如果
如果我有一个类,它的实例占用128位,叫做
Class128Bits
。而我的程序运行在64位计算机上。首先,我调用
let pointer = UnsafeMutablePointer<Calss128Bits>.allocate(capacity: 2)
,内存布局应该如下:000-063 064 bits chaos
064-127 064 bits chaos
128-255 128 bits chaos
256-383 128 bits chaos
如果我调用
pointer.pointee = aClass128Bits
,那么程序将会崩溃,因为前两个指针还没有被初始化。访问它们所指向的内容会导致不可预测的结果。但是如果我调用
pointer.initialize(to: aClass128Bits, count: 2)
,那么指针可以像这样被初始化:000-063 address to offset 128
064-127 address to offset 256
128-255 a copy of aClass128Bits
256-383 a copy of aClass128Bits
然后任何访问都是安全的。然而这并不能解释为什么
UnsafeMutablePointer<Int>
不会崩溃。
原文
指向Int
的指针运行良好,但指向String
的指针会崩溃。
我知道我需要像这样初始化它:
但我看不出为什么需要两次传递"42"
。
在C中,我可能会做类似这样的事情:
char *pointer = (char *)malloc(3 * sizeof(char));
memcpy(pointer, "42", 3);
free(pointer)
如果
allocate
等于 malloc
, free
等于 deallocate
, memcpy
等于 pointee {set}
,那么 initialize
和 deinitialize
实际上是在做什么? 为什么我的代码会崩溃?
pointee
属性,前置条件为_"前置条件:pointee已经用Pointee
类型的实例进行了初始化。"_ 如需更多详细信息,请参考相关的源代码。 - dfribUnsafeMutablePointer<Class128Bits>.allocate(capacity: 2)
只分配了16字节的区域,在64位平台上有2个指针。let pointer = UnsafeMutablePointer<Class128Bits>.allocate(capacity: 2);print(malloc_size(pointer))
->16
。 - OOPernewValue
是一个引用时,引用会被复制。 - OOPer