智能指针

内存泄露:

  • 第一次new的int就会发生内存泄露。(无用,但是占据内存)

#include <iostream>
using namespace std;
int main()
{
    int *pTemp = new int();
    cout << pTemp << endl; // 0x613c20
    *pTemp = 1;
    pTemp = new int();
    delete pTemp;
    cout << pTemp << endl;  // 0x614050
    cout << *pTemp << endl; // 0
    cout << "执行结束了" << endl;
    return 0;
}

迷途指针:

在这里插入图片描述

野指针

在这里插入图片描述

智能指针:

在这里插入图片描述

shared_ptr 共享指针:

  • 多个智能指针可以指向相同对象,该对象和其相关资源会在“最后一个引用被销毁”时候释放。
    在这里插入图片描述

示例代码:

在这里插入图片描述


#include <iostream>
#include <memory>
using namespace std;
int main()
{
    string *s1 = new string("s1");
    shared_ptr<string> ps1(s1);
    shared_ptr<string> ps2;
    ps2 = ps1;

    cout << ps1.use_count() << endl; //2
    cout << ps2.use_count() << endl; //2
    cout << ps1.unique() << endl;    //0

    string *s3 = new string("s3");
    shared_ptr<string> ps3(s3);

    cout << (ps1.get()) << endl; //0x615c20
    cout << ps3.get() << endl;   //0x616080
    swap(ps1, ps3);
    cout << ps1.get() << endl; //0x616080
    cout << ps3.get() << endl; //0x615c20

    cout << ps1.use_count() << endl; //1
    cout << ps2.use_count() << endl; //2
    cout << ps2.get() << endl;       // 0x615c20
    ps2 = ps1;
    cout << ps2.get() << endl;       //0x616080
    cout << ps1.use_count() << endl; //2
    cout << ps2.use_count() << endl; //2
    cout << ps3.use_count() << endl; // 1
    ps1.reset();
    cout << ps1.use_count() << endl; //0
    cout << ps2.use_count() << endl; //1

    return 1;
}

成员函数:

在这里插入图片描述

unique_ptr


#include <iostream>
#include <memory>
using namespace std;
int main()
{
    unique_ptr<string> pu1(new string("hello world"));
    unique_ptr<string> pu2;
    // pu2 = pu1; // 报错
    unique_ptr<string> pu3;
    pu3 = unique_ptr<string>(new string("YOU"));
    cout << "---------------" << endl;

    return 0;
}

weak_ptr

  • weak_ptr是用来解决shared_ptr相互引用时的死锁问题,
  • 如果说两个shared_ptr相互引用,那么这两个指针的引用计数永远不可能下降为0,资源永远不会释放。
  • 它是对对象的一种弱引用,不会增加对象的引用计数
  • 和shared_ptr之间可以相互转化,shared_ptr可以直接赋值给它,它可以通过调用lock函数来获得shared_ptr。

访问:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值