Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What are the disadvantages of using 'static here?

I wonder if a garbage collected language would have a more accurate life time for that object



‘static is a compile time thing for ensuring memory safety. It doesn’t really have anything to say about when the object will be collected. In fact, since Rust/C/C++ applications use precise garbage collection techniques, they’re going to track the lifetime strictly more accurately than a garbage collected language (which I’m presuming you mean tracing GC). Of course you could have a memory leak / reference cycles but memory leaks are possible with tracing GCs as well (just different kinds of leaks but they are a strict subset of the situations that would cause a leak for things like reference counting iirc).

What lifetimes do let you accomplish is more fearless ownership tracking and letting the compiler expire references for you without needing to use any kind of reference counting. And all things being equal, precise garbage tracking results in lower peak and average memory usage.


You wonder based on what? Static will put something in the binary itself and it will be memory mapped in, which won't even need to be directly allocated.


The apostrophe isn’t superfluous. ‘Static in this context refers to static lifetime. Lifetimes have absolutely 0 impact on runtime.


How would you get a static lifetime without a static object?


Unrelated to the above convo, but: An owned object can be bound by a static lifetime, for example. Eg, `fn foo<T: 'static>(t: T){}\n foo(String::new());`


More dangerous / less common, but you can also launder lifetimes through unsafe where you use ‘static to indicate “it’s not possible to verify lifetime at compile time but I promise you this will outlive you”. An example of this would be storing a reference that is reference counted but you don’t want the lifetime to bleed out into the type signature.


Box::leak() will make a &'static. You can also use lazy_static! to dynamically make a static global constant.


Box::leak for one.


I'm not sure what this has to do with the parent post or how it contradicts what I said.

https://doc.rust-lang.org/std/keyword.static.html


You are referring to static variables which have ‘static lifetime. OP is asking about ‘static lifetime and whether GC would somehow collect garbage more precisely (it wouldn’t). You’re basically talking past each other.


'static is a lifetime here.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: