4 ms·
I understood the JS version of this problem, but to see it happen with an address-of operator is just weird. In C if I took the address of a function scoped / t
by lmz 4y ago
I understood the JS version of this problem, but to see it happen with an address-of operator is just weird. In C if I took the address of a function scoped / temporary variable and kept it around it would be very bad.
I guess taking the address "promoted" the shared variable to enable it to survive past the function?
- masklinn 4y agoYes, if you take a reference and it “escapes” the variable gets boxed (promoted to a pointer on the heap).
- yencabulator 4y agoSaid differently: Go puts variables on the stack only when the compiler can prove no references escape the stack frame. Stack is purely an optimization.
- masklinn 4y agoExcept 1. Java is also supposed to do that, and clearly way less successful 2. Escape log is part of the standard baseline tools (it’s just a flag), so it’s not considered anything hidden or arcane 3. Go tends to log escapes, meaning it’s baseline is to stack allocate So it’s a lot more than, say, common subexpression optimisation.
- yencabulator 4y agoThe subtle difference between the two ways of communicating the design: There are cases where the reference does not escape, but the compiler doesn't know how to prove that. So saying "if it escapes it's boxed" is subtly wrong. The default is heap, and only when the compiler can be sure it's safe, things go on the stack.