Search code examples
gounsafe-pointers

in golang, are unsafe.Pointer()s reference counted?


Are unsafe.Pointer()s reference counted and thus protected from being garbage collected?

As in, if I have a string, it exists while it's in scope, if I have a *string, the string exists while the pointer is in scope, but if I have a unsafe.Pointer(&s) (where s is a string or whatever) will s stay in scope as long as the unsafe pointer is still pointing to it?

I found googles that say once you cast to an uintptr it is definitely not, because uintptr is just an int, but I can't find anything definitive one way or another about unsafe.Pointer() probably because the answer is obvious, but I'm not absolutely sure, because I can't find anything that explains it exactly.

and if I cast that unsafe.Pointer to some other pointer type, I assume that doesn't change things?


Solution

  • unsafe.Pointer prevents a pointee from being collected.

    Besides, Golang uses a tracing garbage collector, not reference counting.

    This is not spelled explicitly, but could be inferred from https://pkg.go.dev/unsafe#Pointer

    The doc introduces some unsafe.Pointer usage patterns that are considered safe. In particular, conversion from T1* to Pointer to T2* is valid, provided that T2 is no larger than T1 and the types have “equivalent memory layout”.

    As a consequence, conversion from T* to unsafe.Pointer and back to T* is safe without any constraints. It won’t be safe if unsafe.Pointer didn’t prevent the referenced object from being collected.