go的GC是否将整个对象保留在内存中,而指向字段的内部指针仍然保留?
这样会导致内存泄漏吗?还是go的GC“足够聪明”以注意到不再需要其余对象并将其从内存中清除?
package main
import (
"fmt"
)
const aLot = 500000000
func getInteriorPointer() *int {
type bigStruct struct {
someBigThing [aLot]int
smallThing int
}
b := bigStruct{smallThing: 3}
return &b.smallThing
}
func main() {
p := getInteriorPointer()
// keep using p in the rest of the app,
// never using someBigThing from the struct
fmt.Println(*p)
}
是。内存将一直保留,直到不再引用分配的任何部分为止。
切片技巧给出了通常的示例
删除但不保留订单
a[i] = a[len(a)-1] a = a[:len(a)-1]
注意如果元素的类型是指针或具有指针字段的结构(需要进行垃圾回收),则上述Cut和Delete的实现存在潜在的内存泄漏问题:某些具有值的元素仍被切片a引用,因此无法收集。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句