C++的智能指针之shared_ptr

C++的智能指针之shared_ptr

1、综述

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 的结果.

  auto sp3 = std::make_shared<int>(11);
  printf("sp3=%d\n", *sp3);
  auto sp4 = std::make_shared<std::string>("C++11");
  printf("sp4=%s\n", (*sp4).c_str());

2、成员函数

use_count 返回引用计数的个数
unique 返回是否是独占所有权( use_count 为 1)
swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr sp(new int(1)); sp 与 sp.get()是等价的

以下代码演示各个函数的用法与特点:

std::shared_ptr<int> sp0(new int(2));
std::shared_ptr<int> sp1(new int(11));
std::shared_ptr<int> sp2 = sp1;
printf("%d\n", *sp0);               // 2
printf("%d\n", *sp1);               // 11
printf("%d\n", *sp2);               // 11
sp1.swap(sp0);
printf("%d\n", *sp0);               // 11
printf("%d\n", *sp1);               // 2
printf("%d\n", *sp2);               // 11

std::shared_ptr<int> sp3(new int(22));
std::shared_ptr<int> sp4 = sp3;
printf("%d\n", *sp3);               // 22
printf("%d\n", *sp4);               // 22
sp3.reset();                       
printf("%d\n", sp3.use_count());    // 0
printf("%d\n", sp4.use_count());    // 1
printf("%d\n", sp3);                // 0
printf("%d\n", sp4);                // 指向所拥有对象的地址

std::shared_ptr<int> sp5(new int(22));
std::shared_ptr<int> sp6 = sp5;
std::shared_ptr<int> sp7 = sp5;
printf("%d\n", *sp5);               // 22
printf("%d\n", *sp6);               // 22
printf("%d\n", *sp7);               // 22
printf("%d\n", sp5.use_count());    // 3
printf("%d\n", sp6.use_count());    // 3
printf("%d\n", sp7.use_count());    // 3
sp5.reset(new int(33));                       
printf("%d\n", sp5.use_count());    // 1
printf("%d\n", sp6.use_count());    // 2
printf("%d\n", sp7.use_count());    // 2
printf("%d\n", *sp5);               // 33
printf("%d\n", *sp6);               // 22
printf("%d\n", *sp7);               // 22

std::shared_ptr<int> sp1 = std::make_shared<int>(10);
std::shared_ptr<int> sp2 = std::make_shared<int>(11);
auto sp3 = sp2; 或 auto sp3(sp2);
printf("sp1.use_count = %d\n", sp1.use_count());  // 1
printf("sp2.use_count = %d\n", sp2.use_count());  // 2
printf("sp3.use_count = %d\n", sp3.use_count());  // 2
sp3 = sp1;
printf("sp1.use_count = %d\n", sp1.use_count());  // 2
printf("sp2.use_count = %d\n", sp2.use_count());  // 1
printf("sp3.use_count = %d\n", sp3.use_count());  // 2
  

3、什么时候需要使用share_ptr

(1) 程序不知道自己需要使用多少对象. 如使用窗口类, 使用 shared_ptr 为了让多个对象能共享相同的底层数据.

(2) 程序不知道所需对象的准确类型.
(3) 程序需要在多个对象间共享数据.

4、使用share_ptr的注意事项:

(1) 禁止纯指针给智能指针赋值或者拷贝构造。

int* a=new int(2); 
shared_ptr<int>sp=a;//  error 
sp=a;//    error

(2)shared_ptr多次引用同一数据,会导致两次释放同一内存。如下:

{
    int* pInt = new int[100];
    shared_ptr<int> sp1(pInt);
    // 一些其它代码之后…
    shared_ptr<int> sp2(pInt);
}

(3)使用share_ptr造成循环引用

#include<iostream>
using namespace std;

struct Node
{
    shared_ptr<Node> _pre;
    shared_ptr<Node> _next;

    ~Node()
    {
        cout << "~Node():" << this << endl;
    }
    int data;
};

void FunTest()
{
    shared_ptr<Node> Node1(new Node);
    shared_ptr<Node> Node2(new Node);
    Node1->_next = Node2;
    Node2->_pre = Node1;

    cout << "Node1.use_count:"<<Node1.use_count() << endl;      // 2
    cout << "Node2.use_count:"<< Node2.use_count() << endl;      //2
}

int main()
{
    FunTest();
    system("pause");
    return 0;
}

当出现上述问题时,有以下3种解决方法:

1️⃣当只剩下最后一个引用的时候需要手动打破循环引用释放对象。

2️⃣当parent的生存期超过children的生存期的时候,children改为使用一个普通指针指向parent。

3️⃣使用弱引用的智能指针(weak_ptr)打破这种循环引用。虽然这三种方法都可行,但方法1和方法2都需要程序员手动控制。

5、shared_ptr的实现方式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值