跳转至

4

对标准库的扩充:智能指针和引用计数*

RAII 与引用计数*

引用计数是为了防止内存泄漏而产生的。基本思想是对于动态分配的对象,进行引用计数,每当增加一次对同一个对象的引用,对象的引用计数就会增加一次,每删除一次引用,引用计数就会减一,当一个对象的引用计数减为零时,就自动删除指向的堆内存。

传统 C++ 中,需要手动释放资源。通常的做法是对于一个对象而言,在构造函数中申请空格键,而在析构函数中释放空间,也就是常说的 RAII 资源获取即初始化技术。

当我们需要将对象在自由存储上分配时,传统 C++ 中使用 newdelete,而 C++11 引入了智能指针的概念,使用了引用计数的想法。智能指针包括 std::shared_ptr/std::unique_ptr/std::weak_ptr,包含头文件 <memory>

引用计数不是垃圾回收,引用计数能够尽快收回不再被使用的对象,同时在回收的过程中不会造成长时间等待,更能够清晰明确地表明资源的声明周期。

std::shared_ptr*

std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显式地调用 delete,当引用计数变为零时就会将对象自动删除。

std::make_shared 就能够用来消除显式地使用 new,所以 std::make_shared 会分配创建传入参数中的对象,并返回这个对象类型的 std::shared_ptr 指针。

#include <iostream>
#include <memory>

void foo(std::shared_ptr<int> i)
{
    (*i)++;
}
int main()
{
    // auto pointer = new int(10); // 非法, 不允许直接赋值
    // 构造了一个 std::shared_ptr
    auto pointer = std::make_shared<int>(10);
    foo(pointer);
    std::cout << *pointer << std::endl; // 11

    // 离开作用域前,shared_ptr 会被析构,从而释放内存
    return 0;
}

std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数,并通过 use_count() 来查看一个对象的引用计数。

auto pointer = std::make_shared<int>(10);
auto pointer2 = pointer;    // 引用计数+1
auto pointer3 = pointer;    // 引用计数+1
int *p = pointer.get();             // 这样不会增加引用计数

std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 3
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 3
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 3

pointer2.reset();
std::cout << "reset pointer2:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 2
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0, pointer2 已 reset
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 2

pointer3.reset();
std::cout << "reset pointer3:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 1
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 0, pointer3 已 reset

std::unique_ptr*

std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证代码安全。

std::unique_ptr<int> pointer = std::make_unique<int>(10);   // make_unique 从 C++14 引入
std::unique_ptr<int> pointer2 = pointer;    // 非法
独占即不可复制,我们可以利用 std::move 将其转移给其他的 unique_ptr

#include <iostream>
#include <memory>

struct Foo {
    Foo()      { std::cout << "Foo::Foo" << std::endl;  }
    ~Foo()     { std::cout << "Foo::~Foo" << std::endl; }
    void foo() { std::cout << "Foo::foo" << std::endl;  }
};

void f(const Foo &) {
    std::cout << "f(const Foo&)" << std::endl;
}

int main() {
    std::unique_ptr<Foo> p1(std::make_unique<Foo>());

    // p1 不空, 输出
    if (p1) p1->foo();
    {
        std::unique_ptr<Foo> p2(std::move(p1));

        // p2 不空, 输出
        f(*p2);

        // p2 不空, 输出
        if(p2) p2->foo();

        // p1 为空, 无输出
        if(p1) p1->foo();

        p1 = std::move(p2);

        // p2 为空, 无输出
        if(p2) p2->foo();
        std::cout << "p2 被销毁" << std::endl;
    }
    // p1 不空, 输出
    if (p1) p1->foo();

    // Foo 的实例会在离开作用域时被销毁
}

std::weak_ptr*

std::shared_ptr 依然存在资源无法释放的问题:

#include <iostream>
#include <memory>

class A;
class B;

class A {
public:
    std::shared_ptr<B> pointer;
    ~A() {
        std::cout << "A 被销毁" << std::endl;
    }
};
class B {
public:
    std::shared_ptr<A> pointer;
    ~B() {
        std::cout << "B 被销毁" << std::endl;
    }
};
int main() {
    std::shared_ptr<A> a = std::make_shared<A>();
    std::shared_ptr<B> b = std::make_shared<B>();
    a->pointer = b;
    b->pointer = a;

    return 0;
}

运行结果为 a,b 都不会被销毁,因为其内部的 pointer 同时又引用了 a,b,使得引用计数均变为 2,而离开作用域时,a,b 智能指针被虚构,却智能造成引用计数减一,导致对象指向的内存区域引用计数不为零,而外部已经没有办法找到这块区域,造成内存泄漏。

解决办法就是使用弱引用指针 std::weak_ptr,相比较而言,std::shared_ptr 是一种强引用。弱引用不会引起引用计数增加。std::weak_ptr 没有 *-> 运算符,所以不能对资源进行操作,它的唯一作用就用于检测 std::shared_ptr 是否存在,expired() 方法在资源未被释放时,会返回 true,否则返回 false

总结*

C++11 引入智能指针,一定程度上消除了 new/delete 的滥用。


最后更新: November 26, 2020