C++智能指针 shared_ptr

C++智能指针 shared_ptr

shared_ptr 是一个标准的共享所有权的智能指针, 允许多个指针指向同一个对象. 定义在 memory 文件中(非memory.h), 命名空间为 std.

  shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针, 当然这需要额外的开销:
  

  1. shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针.
  2. 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样.
  3. 开销并不是我们不使用shared_ptr的理由, 永远不要进行不成熟的优化, 直到性能分析器告诉你这一点.

使用方法:

可以使用模板函数 make_shared 创建对象, make_shared 需指定类型(‘<>’中)及参数(‘()’内), 传递的参数必须与指定的类型的构造函数匹配. 如:
 

 std::shared_ptr<int> sp1 = std::make_shared<int>(10);
 std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");

也可以定义 auto 类型的变量来保存 make_shared 的结果.

#include <iostream>
#include <memory>
using namespace std;
int main()
{
    auto sp3 = make_shared<int>(11);
  printf("sp3=%d\n", *sp3);
  auto sp4 = make_shared<std::string>("C++11");
  printf("sp4=%s\n", (*sp4).c_str());
    return 1;
}

sp3=11
sp4=C++11

成员函数

  • use_count 返回引用计数的个数
  • unique 返回是否是独占所有权( use_count 为 1)
  • swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
  • reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
  • get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr sp(new int(1)); sp 与 sp.get()是等价的
    以下代码演示各个函数的用法与特点:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
    shared_ptr<int> sp0(new int(10));
    shared_ptr<int> sp1(new int(2));
    shared_ptr<int> sp2=sp1;
    printf("sp0=%d\n",*sp0);//10
    printf("sp1=%d\n",*sp1);//2
    printf("sp2=%d\n",*sp2);//2
    printf("sp0 use_count=%d\n",sp0.use_count());//1
    printf("sp1 use_count=%d\n",sp1.use_count());//2
    printf("sp2 use_count=%d\n",sp2.use_count());//2
    sp1.swap(sp0);
    printf("sp0=%d\n",*sp0);//2
    printf("sp1=%d\n",*sp1);//10
    printf("sp2=%d\n",*sp2);//2
    printf("sp0 use_count=%d\n",sp0.use_count());//2
    printf("sp1 use_count=%d\n",sp1.use_count());//1
    printf("sp2 use_count=%d\n",sp2.use_count());//2
    return 1;
}

sp0=10
sp1=2
sp2=2
sp0 use_count=1
sp1 use_count=2
sp2 use_count=2
sp0=2
sp1=10
sp2=2
sp0 use_count=2
sp1 use_count=1
sp2 use_count=2

shared_ptr 的赋值构造函数和拷贝构造函数:
  auto r = std::make_shared(); // r 的指向的对象只有一个引用, 其 use_count == 1
  auto q = r; (或auto q(r);) // 给 r 赋值, 令其指向另一个地址, q 原来指向的对象的引用计数减1(如果为0, 释放内存), r指向的对象的引用计数加1, 此时 q 与 r 指向同一个对象, 并且其引用计数相同, 都为原来的值加1.
以下面的代码测试:
  

#include <iostream>
#include <memory>
using namespace std;
int main()
{
    shared_ptr<int> sp0(new int(10));
    shared_ptr<int> sp1(new int(2));
    auto sp2=sp1;
    printf("sp0 use_count=%d\n",sp0.use_count());//1
    printf("sp1 use_count=%d\n",sp1.use_count());//2
    printf("sp2 use_count=%d\n",sp2.use_count());//2    
    sp2=sp0;
    printf("sp0 use_count=%d\n",sp0.use_count());//2
    printf("sp1 use_count=%d\n",sp1.use_count());//1
    printf("sp2 use_count=%d\n",sp2.use_count());//2    
    return 1;
}

sp0 use_count=1
sp1 use_count=2
sp2 use_count=2
sp0 use_count=2
sp1 use_count=1
sp2 use_count=2

何时需要使用 shared_ptr ?

  1. 程序不知道自己需要使用多少对象. 如使用窗口类, 使用 shared_ptr 为了让多个对象能共享相同的底层数据.
#include <iostream>
#include <memory>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<string> v1;  
    {
        vector<string> v2;
        v2.push_back("a");
        v1=v2;//存在数据拷贝
    }
    cout<<v1.size()<<endl;
    return 1;
}
  1. 程序不知道所需对象的准确类型.
  2. 程序需要在多个对象间共享数据.

自定义释放器(函数)

自定义释放器(函数), 它能完成对 shared_ptr 中保存的指针进行释放操作, 还能处理 shared_ptr 的内部对象未完成的部分工作.假设如下是一个连接管理类, 此类由于历史原因, 无法在析构函数中进行断开连接, 此时用自定义的释放器可以很好的完成此工作:

#include <iostream>
#include <memory>
using namespace std;
class CConnnect
{
    public:
    void Disconnect() { cout<<"release resource"<<endl; }
};
void Deleter(CConnnect* obj)
{
    obj->Disconnect(); // 做其它释放或断开连接等工作
    delete obj; // 删除对象指针
}     
int main()
{
    shared_ptr<CConnnect> sps(new CConnnect, Deleter);
    sps.reset();
    cout<<"end flag"<<endl;
    return 1;
}

release resource
end flag

使用 shared_ptr 的注意事项

shared_ptr 作为被保护的对象的成员时, 小心因循环引用造成无法释放资源.

假设 a 对象中含有一个 shared_ptr<CB> 指向 b 对象, b 对象中含有一个 shared_ptr<CA> 指向 a 对象, 并且 a, b 对象都是堆中分配的。
考虑对象 b 中的 m_spa 是我们能最后一个看到 a 对象的共享智能指针, 其 use_count 为2, 因为对象 b 中持有 a 的指针, 所以当 m_spa 说再见时, m_spa 只是把 a 对象的 use_count 改成1; 对象 a 同理; 然后就失去了 a,b 对象的联系.
解决此方法是使用 weak_ptr 替换 shared_ptr . 以下为错误用法, 导致相互引用, 最后无法释放对象

//没有相互引用
#include <iostream>
#include <memory>
using namespace std;
class CA;
class CB;
class CA{
    public:
    CA(){}
    ~CA(){cout<<"CA desctruct"<<endl;}

    void Register(const shared_ptr<CB> &spb)
    {
        m_spb=spb;
    }

    private:
    shared_ptr<CB> m_spb;
};
class CB{
    public:
    CB(){}
    ~CB(){cout<<"CB desctruct"<<endl;}

    void Register(const shared_ptr<CA> &spa)
    {
        m_spa=spa;
    }

    private:
    shared_ptr<CA> m_spa;
};
int main()
{
    shared_ptr<CA> spa(new CA());
    shared_ptr<CB> spb(new CB());
    spa.reset();
    cout<<"end flag"<<endl;
    return 1;
}

CA desctruct
end flag
CB desctruct

//相互引用
#include <iostream>
#include <memory>
using namespace std;
class CA;
class CB;
class CA{
    public:
    CA(){}
    ~CA(){cout<<"CA desctruct"<<endl;}

    void Register(const shared_ptr<CB> &spb)
    {
        m_spb=spb;
    }

    private:
    shared_ptr<CB> m_spb;
};
class CB{
    public:
    CB(){}
    ~CB(){cout<<"CB desctruct"<<endl;}

    void Register(const shared_ptr<CA> &spa)
    {
        m_spa=spa;
    }

    private:
    shared_ptr<CA> m_spa;
};
int main()
{
    shared_ptr<CA> spa(new CA());
    shared_ptr<CB> spb(new CB());
    spa->Register(spb);
    spb->Register(spa);
    spa.reset();
    cout<<"end flag"<<endl;
    return 1;
}

运行上述代码会发现 CA, CB 析构函数都不会打印. 因为他们都没有释放内存.

小心对象内部生成 shared_ptr

class Y : public std::enable_shared_from_this<Y>
 {
 public:
     std::shared_ptr<Y> GetSharePtr()
     {
         return shared_from_this();
     }
 };

对普通的类(没有继承 enable_shared_from_this) T 的 shared_ptr p(new T). p 作为栈对象占8个字节,为了记录( new T )对象的引用计数, p 会在堆上分配 16 个字节以保存引用计数等“智能信息”.
    share_ptr 没有“嵌入(intrusive)”到T对象, 或者说T对象对 share_ptr 毫不知情.
    而 Y 对象则不同, Y 对象已经被“嵌入”了一些 share_ptr 相关的信息, 目的是为了找到“全局性”的那16字节的本对象的“智能信息”.

#考虑下面的代码:
    Y y;
    std::shared_ptr<Y> spy = y.GetSharePtr(); // 错误, y 根本不是 new 创建的
    Y* y = new Y;
    std::shared_ptr<Y> spy = y->GetSharePtr(); // 错误, 问题依旧存在, 程序直接崩溃
#正确用法:
    std::shared_ptr<Y> spy(new Y);
    std::shared_ptr<Y> p = spy->GetSharePtr();
    printf("%d\n", p.use_count()); // 2

小心多线程对引用计数的影响

首先, 如果是轻量级的锁, 比如 InterLockIncrement 等, 对程序影响不大; 如果是重量级的锁, 就要考虑因为 share_ptr 维护引用计数而造成的上下文切换开销.
其次, 多线程同时对 shared_ptr 读写时, 行为不确定, 因为shared_ptr本身有两个成员px,pi. 多线程同时对 px 读写要出问题, 与一个 int 的全局变量多线程读写会出问题的原因一样.

与 weak_ptr 一起工作时, weak_ptr 在使用前需要检查合法性

#include <iostream>
#include <memory>
using namespace std;
class A{
public:
    A(){}
    ~A(){cout<<"descontruct A"<<endl;}
};

int main()
{
    weak_ptr<A> wp;
    {
        shared_ptr<A> spa(new A);
        cout<<spa.use_count()<<endl;//1
        wp=spa;
        cout<<spa.use_count()<<endl;//1
        shared_ptr<A> sp2=wp.lock();
        cout<<spa.use_count()<<endl;//2
    }
    printf("expired:%d\n", wp.expired()); 
    std::shared_ptr<A> sp_null = wp.lock(); //sp_null .use_count()==0;
    return 1;
}

1
1
2
descontruct A
expired:1

上述代码中 sp 和 sp2 离开了作用域, 其容纳的对象已经被释放了. 得到了一个容纳 NULL 指针的 sp_null 对象.
在使用 wp 前需要调用 wp.expired() 函数判断一下. 因为 wp 还仍旧存在, 虽然引用计数等于0,仍有某处“全局”性的存储块保存着这个计数信息.
直到最后一个 weak_ptr 对象被析构, 这块“堆”存储块才能被回收, 否则 weak_ptr 无法知道自己所容纳的那个指针资源的当前状态.

shared_ptr 不支持数组, 如果使用数组, 需要自定义删除器, 如下是一个利用 lambda 实现的删除器:

std::shared_ptr<int> sps(new int[10], [](int *p){delete[] p;});

对于数组元素的访问, 需使要使用 get 方法取得内部元素的地址后, 再加上偏移量取得.

#include <iostream>
#include <memory>
using namespace std;


int main()
{
    shared_ptr<int> sps(new int[10],[](int *p){delete[] p;}); 
    for(size_t i=0;i<10;i++){
    *((int*)sps.get()+i)=i*i;    
    }
    for(size_t i=0;i<10;i++){
    cout<<*((int*)sps.get()+i)<<endl;    
    }
    return 1;
}

0
1
4
9
16
25
36
49
64
81

摘自 https://www.cnblogs.com/diysoul/p/5930361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值