Is there any problem if I hold a member function pointer out of the pointer instance scope

孤街醉人 提交于 2020-01-17 22:26:47

问题


type A struct {
    x1 []int
    x2 []string
}
func (this *A) Test() {
    fmt.Printf("this is: %p, %+v\n", this, *this)
}
func main() {
    var fn func()
    {
        a := &A{}

        a.x1 = []int{1, 2, 3}
        a.x2 = []string{"one", "two", "three"}
        fn = a.Test
    }

    fn()
}

Please see: https://play.golang.org/p/YiwHG0b1hW-

My question is:

  1. Will 'a' be released out of {} local scope?
  2. Is the lifetime of 'a' equal to the one of 'fn'?

回答1:


Go is a garbage collected language. As long as you don't touch package unsafe (or similar like Value.UnsafeAddr() in package reflect), all values remain in memory as long as they are reachable. You don't have to worry about memory management.

That's why it's also safe to return addresses (pointers) of local variables created inside functions. And also it's safe to refer to local variables from function values (closures) that will be out of scope when the function value is executed some time in the future, like this one:

func counter() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

This counter() returns a function (closure) which when called, returns increasing values:

c := counter()
fmt.Println(c())
fmt.Println(c())
fmt.Println(c())

This outputs (try it on the Go Playground):

1
2
3

counter() creates a local variable i which is not returned, but is accessed from the function value returned by it. As long as the returned function value is accessible, the local variable i is not freed. Also if you call counter() again, that creates a new i variable distinct from the previous one.

See related questions:

How to delete struct object in go?

Cannot free memory once occupied by bytes.Buffer



来源:https://stackoverflow.com/questions/59211106/is-there-any-problem-if-i-hold-a-member-function-pointer-out-of-the-pointer-inst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!