Z
ZHANK
指针与内存

智能指针

unique_ptr 独占、shared_ptr 共享、weak_ptr 弱引用、make_unique/make_shared

智能指针

C++ 最重要的特性之一: 智能指针自动管理内存,离开作用域自动释放——告别手动 delete。

学完本章你将: 掌握 unique_ptr(独占)、shared_ptr(共享)、weak_ptr(弱引用)。


unique_ptr —— 独占所有权

cpp
#include <iostream>
#include <memory>

int main() {
    // C++14: make_unique
    auto p = std::make_unique<int>(42);
    std::cout << *p << "\n";  // 42

    // 不能拷贝,只能移动
    auto p2 = std::move(p);   // p 变为空,p2 接管所有权
    // std::cout << *p;       // ❌ p 已被移动

    // 离开作用域自动释放——不需要 delete!
    return 0;
}

shared_ptr —— 共享所有权

cpp
#include <memory>

int main() {
    auto p1 = std::make_shared<int>(42);
    {
        auto p2 = p1;            // 引用计数 +1
        std::cout << *p2 << "\n";
    }  // p2 销毁,引用计数 -1
    // p1 仍然有效
    std::cout << *p1 << "\n";    // 42
}  // 最后一个 shared_ptr 销毁,释放内存

weak_ptr —— 打破循环引用

cpp
struct B;  // 前置声明

struct A {
    std::shared_ptr<B> b_ptr;
    ~A() { std::cout << "A destroyed\n"; }
};

struct B {
    std::weak_ptr<A> a_ptr;  // 用 weak_ptr 而不是 shared_ptr
    ~B() { std::cout << "B destroyed\n"; }
};

// 两者互相引用时,weak_ptr 打破循环——否则永远不会析构

选择指南

场景
独占所有权`unique_ptr`
共享所有权`shared_ptr`
观察但不拥有`weak_ptr`
裸指针只在非所有权场景(函数参数、观察)

💡 现代 C++ 铁律: 永远不要写 newdelete——用 make_unique/make_shared