Does Go guarantee constant addresses?

后端 未结 3 537
挽巷
挽巷 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:29

    There isn't anything in the specification that guarantees this, probably to allow implementations of the language to use compacting garbage collectors in the future. In this golang-nuts thread one of the developers suggests that a compacting GC would be possible provided unsafe.Pointer values were pinned in memory, but this couldn't extend to all unitptr values.

    For the current Go runtime I believe it is true, but relying on it would still be undefined behaviour. There are a few caveats though:

    1. If obj is a zero size type, the value of the expression may not be unique, as described in the spec.

    2. Over the lifetime of a program, a particular uintptr value might refer to different objects.

提交回复
热议问题