new/delete 易漏記憶體、雙重釋放、懸空指標。delete。delete 物件。std::atomic)。class Point { /* ... */ };
class RefPtr { // 輔助類:持有物件指標 + 計數
friend class SmartPtr;
Point *p; int count;
RefPtr(Point *ptr) : p(ptr), count(1) {}
~RefPtr() { delete p; }
};
class SmartPtr { // 使用者介面
RefPtr *rp;
public:
SmartPtr(Point *ptr) : rp(new RefPtr(ptr)) {}
SmartPtr(const SmartPtr& sp) : rp(sp.rp) { ++rp->count; }
SmartPtr& operator=(const SmartPtr& rhs) {
++rhs.rp->count;
if (--rp->count == 0) delete rp;
rp = rhs.rp;
return *this;
}
~SmartPtr() { if (--rp->count == 0) delete rp; }
Point* operator->() { return rp->p; }
Point& operator*() { return *rp->p; }
};
記憶體佈局:每個 SmartPtr 指向同一 RefPtr,RefPtr 指向 Point。

將物件與控制資料(計數器、刪除器、分配器)放在同一記憶體區塊:
templateclass SharedPtr { struct ControlBlock { T *ptr; std::atomic ref_count; ControlBlock(T *p) : ptr(p), ref_count(1) {} }; ControlBlock *ctrl; public: SharedPtr(T *p = nullptr) : ctrl(p ? new ControlBlock(p) : nullptr) {} SharedPtr(const SharedPtr& other) : ctrl(other.ctrl) { if (ctrl) ctrl->ref_count.fetch_add(1, std::memory_order_relaxed); } SharedPtr& operator=(const SharedPtr& other) { if (this != &other) { if (other.ctrl) other.ctrl->ref_count.fetch_add(1, std::memory_order_relaxed); release(); ctrl = other.ctrl; } return *this; } ~SharedPtr() { release(); } void release() { if (ctrl && ctrl->ref_count.fetch_sub(1, std::memory_order_acq_rel) == 1) { delete ctrl->ptr; delete ctrl; } } T* operator->() const { return ctrl->ptr; } T& operator*() const { return *ctrl->ptr; } };
優勢:單次配置、快取友好、支援自訂刪除器/分配器、weak_ptr 自然共享控制塊。
std::shared_ptr 關鍵特性| 特性 | 說明 |
|---|---|
make_shared | 單次配置物件+控制塊,效能最佳 |
weak_ptr | 不增加強引用,打破循環引用 |
enable_shared_from_this | 物件內部安全取得指向自己的 shared_ptr |
| 自訂刪除器 | shared_ptr |
| 別名建構 | 共享控制塊但指向子物件 |