Pointers & References

The different types of pointers and references in the languages.

C++

Rust

Java


{
    // memory freed when ptr_a goes out of scope
    unique_ptr<char> ptr_a(new char('a'));

    // reference counted pointer
    shared_ptr<char> ptr_b(new char('b'));

    // pointer that does not increase reference counts
    weak_ptr<char> ptr_c = ptr_b;

    // memory freed when ptr_d goes out of scope
    // differs from unique_ptr in copy semantics
    auto_ptr<char> ptr_d(new char('d'));
}


{
    // memory freed when ptr_a goes out of scope
    let ptr_a = Box::new('a');

    // reference counted pointer
    let ptr_b = Rc::new('b');

    // pointer that does not increase reference counts
    let ptr_c = ptr_b.downgrade();

    // atomically reference counted pointer
    // can be safely used across threads
    let ptr_e = Arc::new('e');
}


{
    // normal garbage collected reference
    Character ref = new Character('a');

    // reference that does not impact garbage collection
    WeakReference<Character> ptr_c = new WeakReference<>(ref);

    // reference that is stronger than a weak reference
    SoftReference<Character> ref_s = new SoftReference<>(ref);




unique_ptr and auto_ptr in C++ are both very similar to Rust's Box. make_shared() can also be used to generate shared pointers in C++.

All three languages have a concept of a weak pointer or reference that does not impact reference counting or garbage collection. Rust provides an atomic version that can be safely used across threads. Java provides a slightly stronger type of reference SoftReference.