Coding questions · Aurora
Implement a reference-counted smart pointer
This question evaluates understanding of C++ resource management, ownership semantics, RAII, and reference counting implementation within the coding and algorithms domain, emphasizing pointer semantics and object lifetime.
Implement a minimal C++ reference-counted smart pointer similar to std::shared_ptr.
Requirements:
- Create a class template
SharedPtr<T>that manages a heap-allocatedT*. - Use RAII: the managed object must be deleted exactly once when the last
SharedPtrowning it is destroyed. - Support:
- Default constructor (null pointer)
- Constructor from raw pointer
T* - Destructor
- Copy constructor / copy assignment (increase reference count)
- Move constructor / move assignment (transfer ownership, leaving the source null)
T& operator*(),T* operator->(),T* get() constsize_t use_count() constvoid reset(T* p = nullptr)
- Handle self-assignment correctly and avoid memory leaks/double-free.
You may ignore thread-safety unless you explicitly choose to support it.
Reference-Counted Smart Pointer Lifecycle
Simulate SharedPtr ownership operations and return use_count/get query outputs.
Examples
Example 1
Input: ((('new', 'a', 'obj'), ('copy', 'b', 'a'), ('use_count', 'a'), ('reset', 'a'), ('use_count', 'b')),)
Output: [2, 1]
Explanation: Copy increments and reset decrements.
Example 2
Input: ((('new', 'a', 'x'), ('move', 'b', 'a'), ('get', 'a'), ('use_count', 'b')),)
Output: [None, 1]
Explanation: Move leaves source null.
Hints
- A real C++ implementation stores a control block with pointer and count, incrementing on copy and decrementing on destruction/reset.