4 ms·
FWIW, very often the answer in those "returning from a function" situations (in Rust anyway) is to allocate further up the stack, or clone, rather than use a sm
by Jweb_Guru 6y ago
FWIW, very often the answer in those "returning from a function" situations (in Rust anyway) is to allocate further up the stack, or clone, rather than use a smart pointer. In fact, you can nearly always do this, as long as you control enough of the involved code. Use of Rc is intended not only for data that outlives the function in which it's currently defined (because in general, you can define stuff wherever you want), but for data whose lifetime is unpredictable--there either isn't a safe point in your program where you can definitively drop it (this usually more applies to Arc, if it's holding data pointed at by two independent threads), or there is a known safe point but it is too imprecise to be useful to you.
But the latter is pretty subjective; for instance, if you know it's safe to drop something when the program ends, but it might be safe to drop much earlier, in some contexts it still might be worth dropping at the end rather than dealing with the significant overhead of something like Rc or Arc. The reason I recommended arenas is that I find in compilers, often you have cases where you just need to define a scope at some point in your program way higher than when you create the value, and that's what they excel at--letting you initialize stuff with whatever parent scope you want, not arbitrarily restricting you to the function boundary.