4

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?

stu
  • 8,461
  • 18
  • 74
  • 112
  • You might find these tests specifically about escape analysis and the unsafe package informative, https://github.com/golang/go/blob/0d0193409492b96881be6407ad50123e3557fdfb/test/escape_unsafe.go – Brandon Dube Dec 28 '21 at 22:21

1 Answers1

4

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.

Nick Zavaritsky
  • 1,429
  • 8
  • 19
  • sounds good to me thanks. but again, why doesn't somebody just SAY that in the reference, why does it have to be inferred. – stu Dec 28 '21 at 23:39
  • and I realize I should have said "referenced" and not "reference counted" – stu Dec 28 '21 at 23:40
  • @stu: writing language definitions is an art: overspecify and you get a rigid language that can't be improved in the future, underspecify and you get a useless spec, do it right and you get your kind of question. :-) Go doesn't say anything about *how* its GC works, just that it has garbage collection, which leaves implementations free to use ref-counting GC if that turns out to be good someday. – torek Dec 29 '21 at 03:36
  • well, okay yes, I was just trying to be clear. I am aware that the current go implementations use a garbage collector that search-and-destroys in two passes, I was just trying to pick a good term for use in this discussion. but I take your point. – stu Jan 03 '22 at 19:07