Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Idioms and the counted pointer

Notes on the counted-pointer idiom (reference-counting smart pointer): definition, design choices, C++ syntax, problems (circular references) and solutions (weak pointers), with worked traces and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Two sentences: The counted pointer idiom (also called reference-counting smart pointer) is used by engineers to manage dynamic memory and other resources when multiple objects share ownership. It reduces memory errors (leaks, double-delete) and gives clear ownership semantics in designs such as object graphs, caches and shared services.

Key ideas

  • Shared ownership: more than one object may rely on the same resource; we must ensure the resource stays alive while any owner needs it.
  • Counted pointer (definition): a pointer-like object that implements reference counting: it keeps an integer count of how many counted-pointer objects refer to the same resource; the resource is destroyed when this count reaches zero.
  • Non-intrusive vs intrusive counting: non-intrusive means the reference count is stored outside the pointed object (e.g., in a control block). Intrusive means the pointed object itself contains the count field and provides increment/decrement operations.
  • RAII (Resource Acquisition Is Initialization): a design principle where resource lifetime is tied to object lifetime: acquiring in constructor, releasing in destructor. Counted pointer should follow RAII.
  • Copy semantics and assignment: copying a counted pointer increments the shared count; destroying a counted pointer decrements the count and destroys the resource only when count becomes zero. Assignment replaces one reference with another; to be exception-safe, increment the new control block’s count before decrementing the old, and handle self-assignment.
  • Thread-safety: in concurrent code, updates to the reference count must be atomic to avoid race conditions. This often requires atomic integer operations or mutexes; if you implement your own, ensure the right memory-order semantics (e.g., acquire/release) around transitions that destroy the resource.
  • Circular references: when objects reference each other via counted pointers, counts may never reach zero (memory leak). The remedy is to break cycles using weak pointers: observers that do not increment reference count but can test whether resource is still alive.

Exact statements students should remember (treat as definitions/theorems):

  1. Definition (Counted pointer): "Given a resource R and a set S of pointer-like handles, a counted pointer is a handle type P such that there exists a non-negative integer count c(R) maintained per resource; each creation or copy of a handle to R increases c(R) by 1, each destruction or reassignment that drops a handle to R decreases c(R) by 1, and when c(R) reaches 0 the resource R is irrevocably released." Assumptions: copying/assigning operations succeed (no throwing) or are exception-safe via strong guarantee.
  2. Rule of Three/Five (definition): if a class manages a resource, you must implement the destructor, copy constructor, and copy assignment operator (Rule of Three). With move semantics (C++11+), also implement move constructor and move assignment (Rule of Five). This ensures correct reference count updates.

What to draw (class diagram and sequence for exam answers):

  • Class diagram for a non-intrusive counted pointer: draw two boxes, one labelled "Resource control block" with fields: resource_pointer, ref_count (integer), optional weak_count; second box labelled "counted_ptr<T>" with field control_block* and methods: ctor(T*), copy ctor, dtor, operator=, get(), reset(). Draw arrows from counted_ptr to control block and from control block to the resource.
  • Sequence diagram for copy/destroy: horizontal lifelines for original counted_ptr, copy, control block. Show messages: copy invokes increment(ref_count), destroy invokes decrement and possibly destroy resource when ref_count==0.

Implementation choices to be aware of: control block allocation (combined with resource or separate), atomic vs non-atomic counts, intrusive vs non-intrusive API impact on portability and object layout, exception safety in copy/assignment.

Formulas

(Syntax lines to remember; each backticked on its own line, then description.) template<class T> struct counted_ptr { control_block* cb; /*...*/ }; — core structure: holds pointer to a control block that tracks the resource and counts. counted_ptr(T* p) { try { cb = new control_block(p); cb->ref_count = 1; } catch (...) { delete p; throw; } } — construct from raw pointer: allocate control block and set reference count to 1; ensure exception-safety by deleting p if control_block allocation throws (prefer a factory that allocates resource and control block together, e.g., make_counted or std::make_shared for std::shared_ptr). counted_ptr(const counted_ptr& o) { cb = o.cb; if (cb) ++cb->ref_count; } — copy constructor: share control block and increment count. ~counted_ptr() { if (cb && --cb->ref_count == 0) { delete cb->resource; /* if using weak_count, delete control block only when it also reaches 0 */ if (cb->weak_count == 0) delete cb; } } — destructor: decrement count and delete resource if zero; delete the control block only when no weak references remain. counted_ptr& operator=(const counted_ptr& o) { /* increment new then decrement old to be exception-safe */ } — assignment must be implemented to avoid leaks/double-delete; remember strong exception guarantee. counted_ptr(counted_ptr&& o) noexcept : cb(o.cb) { o.cb = nullptr; } counted_ptr& operator=(counted_ptr&& o) noexcept { if (this != &o) { this->reset(); cb = o.cb; o.cb = nullptr; } return *this; } — move operations transfer the control block pointer without changing reference counts. std::atomic<int> ref_count; — use atomic integer for thread-safe increment/decrement. std::weak_ptr<T> — a non-owning observer that does not increment the strong ref_count; it usually increments a separate weak count in the control block and can attempt to lock to a strong counted pointer.

Units: these are programming constructs, no SI units.

Worked examples

Example 1 — Simple trace of copy and delete (non-concurrent, non-intrusive): Given: create p1 = counted_ptr(new A) then p2 = p1; p1 = nullptr; p2 = nullptr; Step-by-step:

  1. p1 = counted_ptr(new A)
    • allocate resource A at address R, allocate control block CB pointing to R; set CB.ref_count = 1.
  2. p2 = p1 (copy)
    • p2.cb = p1.cb (both point to CB). Increment CB.ref_count to 2.
  3. p1 = nullptr (destroy previous p1)
    • decrement CB.ref_count to 1. Since >0, do not delete R.
  4. p2 = nullptr (destroy p2)
    • decrement CB.ref_count to 0. Now delete resource R and then delete CB. Final state: R freed. Answer in exam: show each ref_count value and point of deletion. Final answer: resource deleted when count reached 0.

Example 2 — Circular reference problem (model answer): Design: class Node { counted_ptr<Node> next; counted_ptr<Node> prev; } Two nodes A and B set as A.next=B and B.prev=A using counted_ptr. Trace:

  1. Create A and B separately: each has ref_count 1 for its resource.
  2. Set A.next = B: this increments B's ref_count to 2.
  3. Set B.prev = A: increments A's ref_count to 2.
  4. Drop original external handles to A and B: each object's ref_count remains 2 because they point to each other. Counts never reach 0 -> resources leaked. Exam answer: explain that counted pointers create a cycle that prevents cleanup, then state solution: replace one direction with a weak pointer (weak_ptr) so it does not increment strong count, or break the cycle manually.

Example 3 — Implementation sketch (program trace of assignment with exception-safety): Algorithm (what to write in exam): implement operator= as:

  • if (this->cb == o.cb) return *this;
  • increment o.cb->ref_count (if not null) to secure new resource in case of self-assign or exception.
  • decrement this->cb->ref_count and delete resource if it reaches 0.
  • assign this->cb = o.cb; This order gives the strong exception guarantee because we only drop the old resource after securing the new.

Common mistakes

  • Using counted pointers for every pointer by default; counted pointers have overhead in time and memory — use only when shared ownership is required.
  • Ignoring circular references: students often forget to mention weak pointers or breaking cycles in their answers.
  • Confusing intrusive and non-intrusive counting; be clear which design you mean and how it affects class layout.
  • Violating Rule of Three/Five: for the counted_ptr itself (or any class that manually manages a resource) you must define copy/move/dtor correctly; for classes that merely contain counted_ptr members, prefer the Rule of Zero and rely on compiler-generated operations to manage counts correctly.

For your exam

Question types you will see:

  • Definitions: define counted pointer, reference counting, intrusive vs non-intrusive, RAII, weak pointer.
  • Short notes: explain circular reference and solution, thread-safety considerations, pros and cons.
  • Derivations/algorithms: show code sketch for copy constructor, destructor, and safe assignment operator; show order of operations for exception safety.
  • Programs: implement a minimal counted pointer class in C++ (non-intrusive) and show a small main that creates/copies/destroys objects.
  • Diagrams: class diagram of control block and counted_ptr, and a sequence diagram for copy and destruction.

What a full-marks answer includes:

  • Clear definitions of every term used (resource, ownership, counted pointer, RAII, weak pointer).
  • A correct and exception-safe copy constructor, destructor and assignment operator (or clear pseudocode implementing the Rule of Three/Five).
  • Explanation of intrusive vs non-intrusive and where counts are stored.
  • Discussion of thread-safety and circular references with the correct remedy (weak pointers or manual breaking of cycles).
  • A simple diagram (as described in Key ideas) showing control block and pointers.

Quick check

  1. What happens to the resource when the reference count becomes zero?
  2. Why can counted pointers leak memory when used in object graphs?
  3. How do you make reference counting thread-safe in C++?
    Answers: The resource is destroyed (freed) when count reaches zero; Cycles of counted pointers keep counts >0 so resources are never released (use weak pointers to break cycles); Use atomic increments/decrements (e.g., std::atomic<int>) or mutexes so ref_count updates are thread-safe.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?