C++11 智能指针(unique_ptr、shared_ptr、weak_ptr)

很多人怕写 C/C++ 程序就是因为指针,因为指针给了程序员高度的自由,同样也赋予了高度的责任,稍有不慎就导致内存泄漏。其实写 C++ 可以完全不用指针,尤其 C++ 11 对智能指针作了进一步的升级,在不需要使用任何裸指针的前提下也可以写出高效的 C++ 程序。C++ 11 中定义了unique_ptrshared_ptrweak_ptr三种智能指针 (smart pointer),都包含在<memory>头文件中。智能指针可以对动态分配的资源进行管理,保证任何情况下,已构造的对象最终会销毁,即它的析构函数最终会被调用。

unique_ptr

如名字所示,unique_ptr是个独占指针,C++ 11 之前就已经存在,unique_ptr所指的内存为自己独有,某个时刻只能有一个unique_ptr指向一个给定的对象,不支持拷贝和赋值。下面以代码样例来说明unique_ptr的用法,各种情况都在代码注释给出。

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <map>


void test()
{
    std::unique_ptr<int> up1(new int(11));   // 无法复制的unique\_ptr
    // unique_ptr<int> up2 = up1;        // err, 不能通过编译
    std::cout << *up1 << std::endl;   // 11

    std::unique_ptr<int> up3 = std::move(up1);    // 现在p3是数据的唯一的unique\_ptr

    std::cout << *up3 << std::endl;   // 11
    // std::cout << *up1 << std::endl;   // err, 运行时错误,空指针
    up3.reset();            // 显式释放内存
    up1.reset();            // 不会导致运行时错误
    // std::cout << *up3 << std::endl;   // err, 运行时错误,空指针

    std::unique_ptr<int> up4(new int(22));   // 无法复制的unique\_ptr
    up4.reset(new int(44));  // "绑定"动态对象
    std::cout << *up4 << std::endl; // 44

    up4 = nullptr; // 显式销毁所指对象,同时智能指针变为空指针。与up4.reset()等价

    std::unique_ptr<int> up5(new int(55));
    int *p = up5.release(); // 只是释放控制权,不会释放内存
    std::cout << *p << std::endl;
    // cout << *up5 << endl; // err, 运行时错误,不再拥有内存
    delete p; // 释放堆区资源

    return;
}
shared_ptr

shared_ptr允许多个该智能指针共享 “拥有” 同一堆分配对象的内存,这通过引用计数(reference counting)实现,会记录有多少个 shared_ptr 共同指向一个对象,一旦最后一个这样的指针被销毁,也就是一旦某个对象的引用计数变为 0,这个对象会被自动删除。支持复制和赋值操作。

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <map>


void test()
{
    std::shared_ptr<int> sp1(new int(22));
    std::shared_ptr<int> sp2 = sp1;
    std::cout << "cout: " << sp2.use_count() << std::endl; // 打印引用计数, 2

    std::cout << *sp1 << std::endl;  // 22
    std::cout << *sp2 << std::endl;  // 22

    sp1.reset(); // 显示让引用计数减一
    std::cout << "count: " << sp2.use_count() << std::endl; // 打印引用计数, 1

    std::cout << *sp2 << std::endl; // 22

    return;
}

除了上面出现的use_countreset之外,还有unique返回是否是独占所有权 (use_count 为 1),swap交换两个 shared_ptr 对象 (即交换所拥有的对象),get返回内部对象 (指针) 几个成员函数。

  • make_shared 函数
    最安全的分配和使用动态内存的方法是调用一个名为make_shared的标准库函数。此函数在动态内存中分配一个对象并初始化它,返回指向此对象的shared_ptr。当要用make_shared时,必须指定想要创建的对象的类型或者使用更为简洁的auto,如下:
// 指向一个值为42的int的shared\_ptr
shared\_ptr<int> p3 = make\_shared<int>(42);
// p4指向一个值为"9999999999"的string
shared\_ptr<string> p4 = make\_shared<string>(10,'9');
// p5指向一个值初始化的int,值为0
shared\_ptr<int> p5 = make\_shared<int>();
// p6指向一个动态分配的空vector<string>
auto p6 = make\_shared<vector<string>>();
  • 当进行拷贝或赋值操作时,每个shared_ptr都会记录有多少个其他shared_ptr指向相同的对象:
auto p = make\_shared<int>(42);      //p指向的对象只有p一个引用者
auto q(p);                         //p和q指向相同对象,此对象有两个引用者
weak_ptr

weak_ptr是为配合shared_ptr而引入的一种智能指针来协助shared_ptr工作,它可以从一个 shared_ptr 或另一个 weak_ptr 对象构造,它的构造和析构不会引起引用计数的增加或减少。没有重载 *-> 但可以使用 lock 获得一个可用的shared_ptr对象

weak_ptr的使用更为复杂一点,它可以指向shared_ptr指针指向的对象内存,却并不拥有该内存,而使用weak_ptr成员lock,则可返回其指向内存的一个share_ptr对象,且在所指对象内存已经无效时,返回指针空值 nullptr。

注意:weak_ptr 并不拥有资源的所有权,所以不能直接使用资源。 可以从一个weak_ptr构造一个shared_ptr以取得共享资源的所有权。

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <map>

void check(std::weak\_ptr<int> &wp) {
    std::shared\_ptr<int> sp = wp.lock();  // 转换为shared\_ptr<int>
    if (sp != nullptr) {
      std::cout << "still: " << \*sp << std::endl;
    } else {
      std::cout << "still: " << "pointer is invalid" << std::endl;
    }
}


void test()
{
    std::shared_ptr<int> sp1(new int(22));
    std::shared_ptr<int> sp2 = sp1;
    std::weak_ptr<int> wp = sp1;  // 指向shared\_ptr<int>所指对象

    std::cout << "count: " << wp.use_count() << std::endl;  // count: 2
    std::cout << *sp1 << std::endl;  // 22
    std::cout << *sp2 << std::endl;  // 22
    check(wp);  // still: 22
    
    sp1.reset();
    std::cout << "count: " << wp.use_count() << std::endl;  // count: 1
    std::cout << *sp2 << std::endl;  // 22
    check(wp);  // still: 22

    sp2.reset();
    std::cout << "count: " << wp.use_count() << std::endl;  // count: 0
    check(wp);  // still: pointer is invalid

    return;
}
  • 为什么要使用 weak_ptr
    weak_ptr 解决 shared_ptr 循环引用的问题
    定义两个类,每个类中又包含一个指向对方类型的智能指针作为成员变量,然后创建对象,设置完成后查看引用计数后退出,看一下测试结果:
class CB;
class CA
{
public:
    CA() { cout << "CA() called! " << endl; }
    ~CA() { cout << "~CA() called! " << endl; }
    void set_ptr(shared_ptr<CB>& ptr) { m_ptr_b = ptr; }
    void b_use_count() { cout << "b use count : " << m_ptr_b.use_count() << endl; }
    void show() { cout << "this is class CA!" << endl; }
private:
    shared_ptr<CB> m_ptr_b;
};

class CB
{
public:
    CB() { cout << "CB() called! " << endl; }
    ~CB() { cout << "~CB() called! " << endl; }
    void set_ptr(shared_ptr<CA>& ptr) { m_ptr_a = ptr; }
    void a_use_count() { cout << "a use count : " << m_ptr_a.use_count() << endl; }
    void show() { cout << "this is class CB!" << endl; }
private:
    shared_ptr<CA> m_ptr_a;
};

void test_refer_to_each_other()
{
    shared_ptr<CA> ptr_a(new CA());
    shared_ptr<CB> ptr_b(new CB());

    cout << "a use count : " << ptr_a.use_count() << endl;
    cout << "b use count : " << ptr_b.use_count() << endl;

    ptr_a->set_ptr(ptr_b);
    ptr_b->set_ptr(ptr_a);

    cout << "a use count : " << ptr_a.use_count() << endl;
    cout << "b use count : " << ptr_b.use_count() << endl;
}

// 测试结果
CA() called!
CB() called!
a use count : 1
b use count : 1
a use count : 2
b use count : 2

通过结果可以看到,最后 CA 和 CB 的对象并没有被析构,其中的引用效果如下图所示,起初定义完 ptr_a 和 ptr_b 时,只有①③两条引用,然后调用函数 set_ptr 后又增加了②④两条引用,当 test_refer_to_each_other 这个函数返回时,对象 ptr_a 和 ptr_b 被销毁,也就是①③两条引用会被断开,但是②④两条引用依然存在,每一个的引用计数都不为 0,结果就导致其指向的内部对象无法析构,造成内存泄漏。

解决这种状况的办法就是将两个类中的一个成员变量改为 weak_ptr 对象,因为 weak_ptr 不会增加引用计数,使得引用形不成环,最后就可以正常的释放内部的对象,不会造成内存泄漏,比如将 CB 中的成员变量改为 weak_ptr 对象,代码如下:

class CB
{
public:
    CB() { cout << "CB() called! " << endl; }
    ~CB() { cout << "~CB() called! " << endl; }
    void set_ptr(shared_ptr<CA>& ptr) { m_ptr_a = ptr; }
    void a_use_count() { cout << "a use count : " << m_ptr_a.use_count() << endl; }
    void show() { cout << "this is class CB!" << endl; }
private:
    weak_ptr<CA> m_ptr_a;
};

// 测试结果
CA() called!
CB() called!
a use count : 1
b use count : 1
a use count : 1
b use count : 2
~CA() called!
~CB() called!

通过这次结果可以看到,CA 和 CB 的对象都被正常的析构了,引用关系如下图所示,流程与上一例子相似,但是不同的是④这条引用是通过 weak_ptr 建立的,并不会增加引用计数,也就是说 CA 的对象只有一个引用计数,而 CB 的对象只有 2 个引用计数,当 test_refer_to_each_other 这个函数返回时,对象 ptr_a 和 ptr_b 被销毁,也就是①③两条引用会被断开,此时 CA 对象的引用计数会减为 0,对象被销毁,其内部的 m_ptr_b 成员变量也会被析构,导致 CB 对象的引用计数会减为 0,对象被销毁,进而解决了引用成环的问题。
![][img-1]

  • weak_ptr 注意事项
// 编译错误 // error C2665: “std::weak_ptr<CA>::weak_ptr”: 3 个重载中没有一个可以转换所有参数类型
weak_ptr<CA> ptr_1(new CA());

// 编译错误
// error C2440 : “初始化”: 无法从“std::weak\_ptr<CA>”转换为“std::shared\_ptr<CA>”
shared_ptr<CA> ptr_3 = wk_ptr;

// 编译错误
// 编译必须作用于相同的指针类型之间
wk_ptr_a.swap(wk_ptr_b);         // 调用交换函数

// 编译错误
// 编译必须作用于相同的指针类型之间
wk_ptr_b = wk_ptr_a;

weak_ptr 中只有函数 lock 和 expired 两个函数比较重要,因为它本身不会增加引用计数,所以它指向的对象可能在它用的时候已经被释放了,所以在用之前需要使用 expired 函数来检测是否过期,然后使用 lock 函数来获取其对应的 shared_ptr 对象,然后进行后续操作:

void test2()
{
    shared_ptr<CA> ptr_a(new CA());     // 输出:CA() called!
    shared_ptr<CB> ptr_b(new CB());     // 输出:CB() called!

    cout << "ptr_a use count : " << ptr_a.use_count() << endl; // 输出:ptr_a use count : 1
    cout << "ptr_b use count : " << ptr_b.use_count() << endl; // 输出:ptr_b use count : 1
    
    weak_ptr<CA> wk_ptr_a = ptr_a;
    weak_ptr<CB> wk_ptr_b = ptr_b;
    
    if (!wk_ptr_a.expired())
    {
        wk_ptr_a.lock()->show();        // 输出:this is class CA!
    }

    if (!wk_ptr_b.expired())
    {
        wk_ptr_b.lock()->show();        // 输出:this is class CB!
    }


    wk_ptr_b.reset();                   // 将wk_ptr_b的指向清空
    if (wk_ptr_b.expired())
    {
        cout << "wk_ptr_b is invalid" << endl;  // 输出:wk_ptr_b is invalid 说明改指针已经无效
    }

    wk_ptr_b = ptr_b;
    if (!wk_ptr_b.expired())
    {
        wk_ptr_b.lock()->show();        // 输出:this is class CB! 调用赋值操作后,wk_ptr_b恢复有效
    }

    // 最后输出的引用计数还是1,说明之前使用weak_ptr类型赋值,不会影响引用计数
    cout << "ptr_a use count : " << ptr_a.use_count() << endl; // 输出:ptr_a use count : 1
    cout << "ptr_b use count : " << ptr_b.use_count() << endl; // 输出:ptr_b use count : 1
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值