Skip to content

Q004. How does ownership differ from garbage collection and manual memory management?

Short Answer

Manual management makes correctness depend on explicit allocation and cleanup. Tracing GC reclaims unreachable memory using runtime reachability analysis. Rust instead combines statically checked ownership with RAII-style deterministic destruction. Modern C++ also has RAII, but safe Rust additionally enforces moves, borrowing, and aliasing constraints at compile time.

Deep Dive

The models make different trade-offs:

  • C permits direct allocation and deallocation, with lifetime contracts enforced mainly by the programmer.
  • Modern C++ uses destructors, RAII, and smart pointers, but still allows unchecked raw-pointer ownership and aliasing patterns.
  • Tracing GC discovers unreachable objects at runtime; external resources often still need a separate deterministic cleanup mechanism.
  • Rust determines ordinary cleanup from ownership and Drop, while safe-code moves and borrows are checked statically.

Rust's trade-off is stricter API and data-structure design. Shared graphs, interior mutation, and self-references require explicit abstractions rather than being accepted implicitly.

Internal Model

A tracing collector generally maintains runtime information needed to discover reachability. Rust instead emits drop glue at statically determined points in control flow and does not attach universal GC metadata to owned values.

Rc<T> and Arc<T> add runtime reference counting only when selected. Deliberate leaks, reference cycles, process termination, and suppressed destruction remain possible, so deterministic destruction is not a guarantee that every resource is always released.

Example

rust
struct Resource(&'static str);

impl Drop for Resource {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    {
        let _connection = Resource("connection");
        println!("work");
    } // deterministic drop point
}

Common Mistakes

  • Treating C++ as if idiomatic C++ did not have RAII.
  • Saying deterministic Drop and garbage collection solve exactly the same problem.
  • Claiming ownership makes leaks impossible.

Follow-ups

  • How does Rust ownership differ specifically from std::unique_ptr?
  • Why does tracing reachability not guarantee prompt resource cleanup?
  • When should Rust use Rc<T> or Arc<T>?

References

  • The Rust Programming Language
  • Rust Reference
  • Rustonomicon