Skip to content

Q010. How does ownership determine a value's lifetime?

Short Answer

An owned value becomes live when it is initialized and normally remains live until its current owning path reaches a drop point. A move changes the owning place but does not duplicate the value or end the underlying resource's lifetime. Cleanup can happen earlier through drop, while leaks or suppressed destruction can prevent it entirely.

Deep Dive

For an ordinary local value, the drop point is usually the end of its scope. If ownership moves into another variable, field, collection, or function, cleanup follows that new owner. Passing by value therefore transfers lifecycle responsibility.

std::mem::drop(value) consumes the value and ends its usable lifetime at that call. Conversely, mem::forget, ManuallyDrop, reference cycles, or process termination can prevent normal destruction.

The lifetime of a value is not the same as the lifetime of a borrow. Non-lexical lifetimes can end a borrow after its last use, but they do not generally cause an owned local with Drop to be destroyed immediately after its last use.

Internal Model

The compiler calculates drop scopes and elaborates cleanup paths. A move marks the source place uninitialized and makes the destination responsible for eventual destruction.

The optimizer may shorten the physical storage lifetime or reuse memory when behavior is unchanged, but it must preserve observable destruction semantics. Releasing a stack frame and running a value's destructor are separate operations.

Example

rust
fn main() {
    let first = String::from("resource");
    let second = first;

    println!("{second}");
    drop(second); // the String is destroyed here
}

Common Mistakes

  • Saying a moved resource is destroyed and recreated at the destination.
  • Confusing a borrow's lifetime with the owned value's drop scope.
  • Assuming the compiler always drops an owned value immediately after its last use.

Follow-ups

  • What is the difference between a value lifetime, borrow lifetime, and storage lifetime?
  • How are temporary drop scopes determined?
  • What happens to ownership when a value is returned from a function?

References

  • The Rust Programming Language
  • Rust Reference
  • Rust Standard Library