使用 uintptr 作为弱引用的风险如何?
时间:2024-02-26
浏览:382
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《使用 uintptr 作为弱引用的风险如何?》,聊聊,我们一起来看看吧!
问题内容
我想在 Go 中实现弱引用,以便我可以使用终结器来检测何时不再需要数据结构并能够存储/清理数据。
我发现这样做的一种方法是使用 uintptr 作为映射键,这样当调用终结器时,我可以使用传递给终结器函数的指针值访问/清理数据。这样做安全吗?
我想我的问题是:Go 使用移动垃圾收集器吗?或者会吗?
解决方案
您自己引用的 927571887 的 The link 提供了您想问的问题的答案:不要给客户端一个指向您想要大惊小怪的底层对象的指针,而是给他们一个指向包装对象的指针: p>
type internal struct {
// all the internal stuff goes here
}
// change the name Wrapper below to something more suitable
type Wrapper struct {
*internal // or p *internal if you want to be overly verbose
}
func NewWhatever(/*args*/) *Wrapper {
p := &Wrapper{...} // fill this part in
runtime.SetFinalizer(p, wrapperGotCollected)
return p
}
func wrapperGotCollected(p *Wrapper) {
// since p itself is about to be collected,
// **p (or *((*p).p)) is no longer accessible by
// the user who called NewWhatever(). Do
// something appropriate here.
}
请注意,这不在 *internal 上使用终结器,而是在 *wrapper 上使用终结器:在调用 wrappergotcollected 时,保证 *internal 对象本身仍然存在,因为 p 本身还没有被 gc 处理(它已经完成了一半,一旦 wrappergotcollected 返回,或者不久之后,剩下的部分就会完成)。
unsafe documentation 允许 gc 在内存中移动值。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 uintptr 作为弱引用的风险如何?》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
