变量赋值
基础类型
复制值
let a = 0
var a2 = a
a2 += 1
// a: 0, a2: 1
int a = 0;
int a2 = a;
a2 += 1;
// a: 0, a2: 1
// arm64, AT&T
_main:
sub sp, sp, #64
stp x29, x30, [sp, #48]
add x29, sp, #48
// int a = 0;
mov w8, #0
str w8, [x29, #-4]
// int a2 = a;
ldr w8, [x29, #-4]
str w8, [x29, #-4*2]
// a2 += 1;
ldr w8, [x29, #-4*2]
add w8, w8, #1
str w8, [x29, #-4*2]
ldp x29, x30, [sp, #48]
add sp, sp, #64
ret
栈上复合类型
复制值
struct S {
var a: Int
}
let s = S(a: 0)
var s2 = s
s2.a += 1
// s.a: 0, s2.a: 1
struct S {
int a;
};
struct S s = {0};
struct S s2 = s;
s2.a += 1;
// s.a: 0, s2.a: 1
// arm64, AT&T
_main:
sub sp, sp, #64
stp x29, x30, [sp, #48]
add x29, sp, #48
// struct S s = {0};
mov w8, #0
str w8, [x29, #-4]
// struct S s2 = s;
ldr w8, [x29, #-4]
str w8, [x29, #-4*2]
// s2.a += 1;
ldr w8, [x29, #-4*2]
add w8, w8, #1
str w8, [x29, #-4*2]
ldp x29, x30, [sp, #48]
add sp, sp, #64
ret
堆上复合类型
复制值
堆上复合类型复制值的时候,分配新的堆内存,并把值完全复制了一份
protocol Copyable {
func copy() -> Self
}
class C: Copyable {
var a: Int
required init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
let c = C(a: 0)
let c2 = c.copy()
c2.a += 1
// c.a: 0, c2.a: 1
struct C {
int a;
};
struct C *c = malloc(sizeof(struct C));
c->a = 0;
struct C *c2 = malloc(sizeof(struct C));
c2->a = c->a;
c2->a += 1;
// c.a: 0, c2.a: 1
复制地址/引用
堆上复合类型复制地址/引用的时候,仅把堆内存地址复制了一份放在栈上
两个指针变量共享同一份堆内存,因此修改其中一个指向的值,也会更改另一个指向的值
class C {
var a: Int
init(a: Int) {
self.a = a
}
}
let c = C(a: 0)
let c2 = c
c2.a += 1
// c.a: 1, c2.a: 1
struct C {
int a;
};
struct C *c = malloc(sizeof(struct C));
c->a = 0;
struct C *c2 = c;
c2->a += 1;
// c.a: 1, c2.a: 1