Understanding shared_ptr reference counting in C++
This easy C++ language-knowledge question tests your grasp of how shared_ptr tracks object ownership and lifecycle. It's a foundational concept that appears in technical interviews because shared pointers are ubiquitous in production systems, and misunderstanding their reference-counting behaviour leads to memory leaks and dangling pointers.
To answer questions like this, you need to trace what happens when a shared_ptr is constructed, assigned, copied, or goes out of scope. The reference count reflects how many shared_ptr instances (and control blocks) point to the same underlying object. Pay attention to edge cases around default construction, null pointers, and the distinction between the object itself and the shared_ptr wrapper.
- Default construction and null state
- Ownership semantics and control-block lifecycle
- How copies and moves affect the reference count
- Distinction between reference count and use count