在Golang中,`unsafe.Pointer()`是否具有引用计数?

huangapple go评论96阅读模式
英文:

in golang, are unsafe.Pointer()s reference counted?

问题

unsafe.Pointer()是引用计数的吗,因此受到保护,不会被垃圾回收?

也就是说,如果我有一个字符串,在其作用域内它存在;如果我有一个*string,只要指针在作用域内,字符串就存在;但是如果我有一个unsafe.Pointer(&s)(其中s是一个字符串或其他类型),只要不安全指针仍然指向它,s会一直存在吗?

我找到一些谷歌的结果,说一旦转换为uintptr,它肯定不是引用计数的,因为uintptr只是一个int,但是我找不到关于unsafe.Pointer()的确切解释,可能是因为答案很明显,但我不能确定,因为我找不到确切的解释。

如果我将那个unsafe.Pointer转换为其他指针类型,我猜那不会改变情况吗?

英文:

Are unsafe.Pointer()s reference counted and thus protected from being garbage collected?

As in, if I have a string, it exists while it's in scope, if I have a *string, the string exists while the pointer is in scope, but if I have a unsafe.Pointer(&s) (where s is a string or whatever) will s stay in scope as long as the unsafe pointer is still pointing to it?

I found googles that say once you cast to an uintptr it is definitely not, because uintptr is just an int, but I can't find anything definitive one way or another about unsafe.Pointer() probably because the answer is obvious, but I'm not absolutely sure, because I can't find anything that explains it exactly.

and if I cast that unsafe.Pointer to some other pointer type, I assume that doesn't change things?

答案1

得分: 4

unsafe.Pointer可以防止指针指向的对象被回收。

此外,Golang使用的是追踪垃圾收集器,而不是引用计数。

虽然这并没有明确说明,但可以从https://pkg.go.dev/unsafe#Pointer中推断出来。

该文档介绍了一些被认为是安全的unsafe.Pointer使用模式。特别是,从T1到Pointer到T2的转换是有效的,前提是T2不比T1大,并且类型具有"等效的内存布局"。

因此,从T到unsafe.Pointer的转换,再从unsafe.Pointer转回T是安全的,没有任何限制。如果unsafe.Pointer没有阻止引用对象被回收,那么这种转换就不安全。

英文:

unsafe.Pointer prevents a pointee from being collected.

Besides, Golang uses a tracing garbage collector, not reference counting.

This is not spelled explicitly, but could be inferred from https://pkg.go.dev/unsafe#Pointer

The doc introduces some unsafe.Pointer usage patterns that are considered safe. In particular, conversion from T1* to Pointer to T2* is valid, provided that T2 is no larger than T1 and the types have “equivalent memory layout”.

As a consequence, conversion from T* to unsafe.Pointer and back to T* is safe without any constraints. It won’t be safe if unsafe.Pointer didn’t prevent the referenced object from being collected.

huangapple
  • 本文由 发表于 2021年12月29日 06:13:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/70513096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定