Smart Pointers in C++

Words: 1383

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.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <memory>
using namespace std;

int main() {
    auto p1 = make_unique<int>(42);  // 推荐用 make_unique
    // auto p2 = p1;                  // 编译错误!不可拷贝
    auto p2 = move(p1);              // 所有权转移,p1 变为 nullptr

    // 自定义删除器
    auto deleter = [](FILE* f) { if (f) fclose(f); };
    unique_ptr<FILE, decltype(deleter)> fp(fopen("test.txt", "r"), deleter);
    // 带自定义删除器的 unique_ptr 会多占一个删除器的大小
    return 0;
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
shared_ptr 实例:
┌──────────┐     ┌──────────────────┐
│ ptr      │ ──→ │  托管对象         │
├──────────┤     └──────────────────┘
│ ctrl_blk │ ──→ ┌──────────────────┐
└──────────┘     │ strong_count (1) │ ← shared_ptr 的数量
                 │ weak_count   (0) │ ← weak_ptr 的数量 + 1(如果有 weak_ptr)
                 │ deleter          │
                 │ allocator        │
                 └──────────────────┘

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:

cpp
1
2
3
4
// 危险!不要这样做
auto* raw = new int(42);
shared_ptr<int> sp1(raw);
shared_ptr<int> sp2(raw);  // 独立控制块!两个都会尝试 delete raw

The correct approach is to use make_shared or copy from an existing shared_ptr:

cpp
1
2
auto sp1 = make_shared<int>(42);  // 推荐:一次分配,对象+控制块合在一起
auto sp2 = sp1;                    // 共享同一个控制块

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():

cpp
1
2
3
4
5
6
7
8
9
class Node : public enable_shared_from_this<Node> {
public:
    shared_ptr<Node> getPtr() {
        return shared_from_this();  // 正确的做法
    }
};

auto n = make_shared<Node>();
auto n2 = n->getPtr();  // 共享同一个控制块

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class B; // 前向声明

class A {
public:
    shared_ptr<B> ptr_to_b;  // A 持有 B
    ~A() { cout << "A 析构" << endl; }
};

class B {
public:
    // shared_ptr<A> ptr_to_a; // 错误!循环引用导致永远不会析构
    weak_ptr<A> ptr_to_a;     // 正确:弱引用不阻止析构
    ~B() { cout << "B 析构" << endl; }
};

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:

cpp
1
2
3
4
5
if (auto sp = weak.lock()) {
    sp->doSomething();           // 对象仍然存活
} else {
    // 对象已被销毁
}

Performance Comparison

TypesizeofConstruct/DestructDereferenceCopyTypical overhead
unique_ptrraw pointer size (8B)O(1)same as raw pointernon-copyable, move is O(1)zero extra overhead (without a custom deleter)
shared_ptr2× raw pointer (16B)Atomic Operation ±1same as raw pointeratomic inc(+1)control block heap allocation + atomic reference counting
weak_ptr2× raw pointer (16B)does not modify countsrequires lock() to promote—requires access through the control block

A few key points:

  • The reference counting operations of shared_ptr are 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 use boost::local_shared_ptr or simply pass by reference to avoid copying.
  • Dereferencing is unaffected — whether unique_ptr or shared_ptr, ptr->foo() is as fast as a raw pointer; the overhead is only in construction/destruction/copy/assignment.
  • make_shared is better than new + constructing a shared_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:

  1. If you can use unique_ptr, don’t use shared_ptr. The lifetime of most objects is clear (whoever creates it destroys it), and exclusive ownership is already enough. unique_ptr is zero-overhead — you get memory safety for free.

  2. When sharing is needed, prefer passing by reference over copying a shared_ptr. Every copy of a shared_ptr is an atomic increment, and on hot paths it adds up.

  3. Use a shared_ptr + weak_ptr combination for asynchronous callbacks + LRU caches. For example, the in-memory cache of player data: the main table holds it with shared_ptr, other places observe it with weak_ptr; if the player goes offline, weak_ptr.lock() returns null and the entry is naturally evicted.

  4. Avoid holding the container/manager that owns an object with a shared_ptr inside the object itself. This is a hotbed of circular references; don’t cut corners where a weak_ptr is called for.

  5. Object Pool + unique_ptr is a pattern well suited to game servers. Pre-allocate a batch of objects, let unique_ptr manage their lifetimes, and use a custom deleter to release them back to the pool instead of really deleteing 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.

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...