Does Go guarantee constant addresses?

后端 未结 3 554
挽巷
挽巷 2021-02-07 13:22

Given an object obj is there a guarantee that

uintptr(unsafe.Pointer(&obj))

will always evaluate to the same value regardless of w

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 14:06

    There is no such guarantee, exactly so that it is possible to implement a moving collector.

    In fact, although the garbage collector does not move heap objects today, in Go 1.3 stacks can move when needing to grow, so it is entirely possible that

    var obj int
    fmt.Println(uintptr(unsafe.Pointer(&obj)))
    bigFunc()
    fmt.Println(uintptr(unsafe.Pointer(&obj)))
    

    will print two different pointers, because bigFunc grew the stack, causing obj and everything else on the stack to move.

提交回复
热议问题