What are smart pointers?

Smart pointers don't have a very precise meaning so it's more of a "I know it when I see it" thing.

In general, I would say a smart pointer...

  • Wraps some other value
  • Implements Deref and DerefMut (where applicable) to give you a reference to that value, with dereferencing being a cheap operation which returns the same reference every time
  • Manages the wrapped value in some way (e.g. Box manages memory, RefCell's Ref manages sharing xor mutability)
  • Almost all uses of the smart pointer go through the Deref implementation, with next to no method calls which take the smart pointer itself as a receiver

Using that definition, String and Cow would be considered smart pointers, but something like RefCell or AtomicPtr wouldn't.

This concept is orthogonal to wide/fat pointers (i.e. pointer + metadata).

4 Likes