Notes

Thoughts, write-ups, and things worth remembering.

Smart pointers

#cpp#memory Updated Sep 16, 2026

Three flavors, three ownership models. Picking the wrong one is how you get either a leak or a needless performance hit.

Owner countCostUse when
unique_ptrexactly onefree (just a pointer)default choice - single, clear owner
shared_ptrmany, ref-countedatomic refcount on copy/destroyownership genuinely shared
weak_ptrzero (observer only)cheap to checkpeek at a shared_ptr without keeping it alive

Default to unique_ptr. Reach for shared_ptr only when you genuinely can’t name one owner. weak_ptr almost always shows up paired with a shared_ptr it’s watching.

RAII