Is there a difference how pointers work in Go and C++, will pointers change after gc?
I want to know the specific relationship between pointers and memory in Go. If you have relevant information or source code explanations, thank you very much.
Is there a difference how pointers work in Go and C++, will pointers change after gc?
I want to know the specific relationship between pointers and memory in Go. If you have relevant information or source code explanations, thank you very much.
The language specification does not say anything whether pointers should stay invariant. Which means you should not rely / build on this.
What you have guarantee of is that if pointers change after a garbage collection cycle, or if the runtime changes them due to memory allocation / release, the pointers you have in your variables will be updated to reflect the changes.
There is a hint in the documentation of unsafe.Pointer
that pointers may change:
A uintptr is an integer, not a reference. Converting a Pointer to a uintptr creates an integer value with no pointer semantics. Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed.
In practice the garbage collector won't go around and change pointers all the time, that would be an unnecessary overhead. But it may reorder objects in memory if a lot of them is freed and compacts the memory, or there's a "pressure" to free unused memory (e.g. due to a call to debug.FreeOSMemory()
).