Fastest way to hold a reference

What is required is a container object which either is empty or holds a single reference to a specified type. The reference must be popped out when its lifetime ends (just a pop() like method is enough).

First thing that comes to mind is a vector (or a vecdeque or a stack), simply push the reference and before it goes out of scope, pop it.

Any better suggestions for this (more efficient methods probably)? Is it possible to free the variable inside a Box object then use the box later?

What do you need the reference for? Do you need the container to own the object by-value? Would an Option<&T> suffice?

Yes, it is. If you want to use it e.g. across function calls, where the compiler can't prove that it is properly re-initialized before the next use, you can make a Box<Option<T>> as well and .take() it.

1 Like

Oh yeah, I totally forgot about Options.

Basically the container's lifetime needs to not be affected by any operations on the owner. So before mutating the owner, I guess setting the variable to None would suffice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.