[英]how a pointer to a struct member keeps the struct alive in Go
Given the following golang code:给定以下 golang 代码:
type Pointer struct { x, y int }
func foo(p *Pointer) *int {
return &p.y
}
CompilerExplorer shows that return &p.y
compiles to CompilerExplorer显示
return &p.y
编译为
TESTB AL, (AX)
ADDQ $8, AX
RET
It's easy to understand.这很容易理解。
TESTB
is a null check, then ADDQ
produce a pointer to py
by adding offset of Pointer::y
to p
. TESTB
是一个空检查,然后ADDQ
通过将Pointer::y
的偏移量添加到p
来生成指向py
的指针。
What I don't understand is, given a pointer to py
, how does the garbage collector knows it's not just an arbitrary *int
, but a pointer to a Pointer::y
, so p
must remain alive as long as a pointer to py
is still alive?我不明白的是,给定一个指向
py
的指针,垃圾收集器如何知道它不仅仅是一个任意的*int
,而是一个指向Pointer::y
的指针,所以只要指向py
的指针p
就必须保持活动状态还活着?
After reading the source code I found the answer.阅读源代码后,我找到了答案。
p
, base address of span b
and element size of span s
, we know the pointer is pointing n-th element in the span, where n = (p - b) / s
.p
、 span b
的基地址和 span s
元素大小,我们知道指针指向 span 中的第 n 个元素,其中n = (p - b) / s
。b + s * n
, which needs to be marked as alive.b + s * n
中第 n 个对象的地址,需要标记为活动的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.