To solve the memory leak problem caused by forgetting to delete objects created with new, C++11 introduced Smart Pointers. The core idea is RAII — bind the lifetime of a raw pointer to the lifetime of a stack object, so that when the stack object is destroyed, the heap memory is released automatically.
unique_ptr — Exclusive Ownership
unique_ptr has exclusive ownership of an object and is non-copyable (the copy constructor and copy assignment are = delete); it can only be moved. This restriction makes its overhead exactly the same as a raw pointer — no Reference Counting, no control block, and its sizeof is the size of a raw pointer.
| |
Use cases: factory function return values, storing objects in containers, the PIMPL idiom, local dynamic allocation inside a function.
shared_ptr — Shared Ownership
shared_ptr allows multiple pointers to share the same object and manages the lifetime through Reference Counting. When the last shared_ptr is destroyed, the object is released.
Control Block
The underlying core of shared_ptr is a control block, allocated on the heap, containing two counts:
| |
Each shared_ptr occupies two pointer sizes (a pointer to the object + a pointer to the control block), 16 bytes total (on a 64-bit system).
The timing of control block creation is critical: the control block is created when a shared_ptr is constructed from a raw pointer. So if you construct multiple shared_ptrs from one raw pointer, multiple independent control blocks are created, causing a double-free:
| |
The correct approach is to use make_shared or copy from an existing shared_ptr:
| |
make_shared has an additional advantage: it merges the managed object and the control block into a single memory allocation, which not only reduces the number of allocations but also improves cache locality. The cost is that if a weak_ptr exists, even after all shared_ptrs are destroyed, the whole block of memory cannot be released until all weak_ptrs are gone (because the object and the control block are the same block of memory).
shared_from_this
When a class needs to return a shared_ptr to itself from a member function, you cannot directly use shared_ptr<T>(this) (that would create a duplicate control block); instead you should inherit from enable_shared_from_this<T> and call shared_from_this():
| |
enable_shared_from_this stores a weak_ptr internally, and shared_from_this() constructs a shared_ptr from it. Note: when calling shared_from_this(), the object must already be managed by a shared_ptr, otherwise a bad_weak_ptr exception is thrown.
weak_ptr — Breaking Circular References
weak_ptr does not increment the strong reference count; it points to an object managed by a shared_ptr but does not own it. Its main purpose is to break circular references:
| |
Typical scenarios: bidirectional associations (parent-child, observer pattern), cache systems, and avoiding lifetime extension in asynchronous callbacks.
When accessing an object through a weak_ptr, you must first call lock() to try to promote it to a shared_ptr:
| |
Performance Comparison
| Type | sizeof | Construct/Destruct | Dereference | Copy | Typical overhead |
|---|---|---|---|---|---|
unique_ptr | raw pointer size (8B) | O(1) | same as raw pointer | non-copyable, move is O(1) | zero extra overhead (without a custom deleter) |
shared_ptr | 2× raw pointer (16B) | Atomic Operation ±1 | same as raw pointer | atomic inc(+1) | control block heap allocation + atomic reference counting |
weak_ptr | 2× raw pointer (16B) | does not modify counts | requires lock() to promote | — | requires access through the control block |
A few key points:
- The reference counting operations of
shared_ptrare atomic (thread-safe), and Atomic Operations cost dozens of CPU cycles more than a plain++/--. If you are sure it is single-threaded, you can useboost::local_shared_ptror simply pass by reference to avoid copying. - Dereferencing is unaffected — whether
unique_ptrorshared_ptr,ptr->foo()is as fast as a raw pointer; the overhead is only in construction/destruction/copy/assignment. make_sharedis better thannew+ constructing ashared_ptr: it saves one heap allocation, and the object and control block sit on the same cache line.
Choosing for Game Servers
Game servers are highly sensitive to latency and memory, so the selection strategy is as follows:
If you can use
unique_ptr, don’t useshared_ptr. The lifetime of most objects is clear (whoever creates it destroys it), and exclusive ownership is already enough.unique_ptris zero-overhead — you get memory safety for free.When sharing is needed, prefer passing by reference over copying a
shared_ptr. Every copy of ashared_ptris an atomic increment, and on hot paths it adds up.Use a
shared_ptr+weak_ptrcombination for asynchronous callbacks + LRU caches. For example, the in-memory cache of player data: the main table holds it withshared_ptr, other places observe it withweak_ptr; if the player goes offline,weak_ptr.lock()returns null and the entry is naturally evicted.Avoid holding the container/manager that owns an object with a
shared_ptrinside the object itself. This is a hotbed of circular references; don’t cut corners where aweak_ptris called for.Object Pool +
unique_ptris a pattern well suited to game servers. Pre-allocate a batch of objects, letunique_ptrmanage their lifetimes, and use a custom deleter toreleasethem back to the pool instead of reallydeleteing them.
Q&A
Q1: What are the underlying implementations, use cases, and performance overheads of shared_ptr, unique_ptr, and weak_ptr respectively?
unique_ptr: Exclusive ownership; underneath it is just a raw pointer (without a custom deleter, its sizeof is the same as a raw pointer), non-copyable and movable only. Zero overhead — dereferencing is exactly the same as a raw pointer. Applies to: factory function returns, PIMPL, local dynamic allocation, Object Pools.
shared_ptr: Shared ownership; underneath it is a pointer to the object + a pointer to the control block (16 bytes total). The control block holds the atomic strong reference count (strong_count) and the weak reference count (weak_count). Copying does an atomic inc; destruction does an atomic dec and releases the object when it reaches 0. The overhead comes from the heap allocation of the control block and the atomic operations. Applies to: cases with multiple owners where it is impossible to determine who releases last.
weak_ptr: Does not own the object; works with shared_ptr to break circular references. Underneath it is also two pointers, same as shared_ptr; it accesses through the control block, and when used you need lock() to promote it to a shared_ptr and check whether the object is still alive. Applies to: observer, caches, and bidirectional associations where a cycle needs to be broken.
Q2: How would you choose in a game server?
Game server choices: If you can use unique_ptr, don’t use shared_ptr — exclusive ownership covers most scenarios at zero overhead; when sharing is needed, prefer passing by reference to avoid atomic counting; use a shared_ptr + weak_ptr combination for asynchronous callbacks/caches; Object Pools combined with unique_ptr’s custom deleter are very practical.