2 ms·
> All objects in general are allocated in the same place, and you can always safely share a reference to an object (from a use-after-free perspective, not paral
by amluto 4y ago
> All objects in general are allocated in the same place, and you can always safely share a reference to an object (from a use-after-free perspective, not parallelism etc).
Every other language I can think of that does this spells it in a materially different way, kind of like this (intentionally not matching any particular language):
x = func();
y = x;
Now x and y are references to the same thing, each one is sufficient to keep the referent alive, and they are on equal footing.
This includes every GC language I’m familiar with except Go. It also includes C++ when using any sort of pointer (including smart pointers) and even plain references (with the obvious caveats about returning a reference to a local variable being nonsense in C++). It includes Swift with ARC. And it includes functional languages, pure and otherwise. If you return a (correct) reference to an object that would otherwise be local, you are returning the same type as the original local variable.
I think go is unusual in that it looks more like this:
x = func();
y = &x:
Here x has type int (or whatever). y has type int. Yet x keeps that integer alive, and so does y. x and y refer to the same thing. &x and &y are not equivalent.
So I think woodruffw is reasonable to find returning the address of a local variable weird coming from pretty much any background.
- tsimionescu 4y agoThe one thing that Go supports that I think no other GC language does is the ability to create a reference to a value at will. However, similar things can be done in C# for example by capturing a local variable in a closure, even if that variable is of a value type (struct). The closure then becomes something similar to a Go reference to that value, and you are still free to return it with no UB or other problems. Either way, if your mental model is adjusted to the GC memory model, there is nothing special going on here. The weirdness comes only out of tying an object's lifetime to its scope. Scope is irrelevant to lifetime in GC languages, where lifetime is tied to (live) references to that object. So, if a reference to an object "escapes" its scope, that object will live beyond the scope where it was originally declared - nothing strange about that.