Smart Pointers: Closing Words

Shared Pointers: When To Use Which?

Now when to use which pointer?

⟶ no definitive answer, but …

Answer 1: performance, and designwise correctness

  • Always use std::unique_ptr<> ⟶ clearly defined ownership

  • Pass object around as pointer (uptr->get())

  • Use std::shared_ptr<> only if we have real shared ownership

Answer 2: programming efficiency

  • Don’t waste a thought on ownership, simply write it

  • Always use std::shared_ptr<>

Resource Usage

How do std::shared_ptr and std::unique_ptr compare?

  • std::unique_ptr

    • Small - size of a pointer

    • Operations compile away entirely

    • No excuse not to use it

    • Have to think more though

  • std::shared_ptr

    • Size of two pointers

    • Copying manipulates the resource count. Expensive: atomic instructions - memory barriers

    • Copying manipulates non-adjacent memory locations

    • Usage is very easy (no std::move and such)

    Attention

    • Cyclic references possible!

    • No garbage collection as in Java

    • ⟶ Leak!!

    See below …