C++标准库学习之 shared_ptr 智能指针

54 阅读2分钟

Class shared_ptr 是实现的共享式拥有的概念,如果存在多个 shared_ptr 指向同一个对象,对象和他内部的资源会在最后一个 shared_ptr 回收时资源被释放, 他的主要应用场景是 多个地方使用同一个对象但是又不想自己去管理指针的回收

shared_ptr 的使用方式与 原始的pointer 的使用方式是一致的, 可以使用他的赋值 拷贝 ,也可以使用他的 * , -> 访问他的对象

下面来简单介绍一下他的使用方法

shared_ptr 在 #include < memory > 库下


#include <iostream>
#include <string>
#include <memory>

    
using namespace std;

int main() {

//    auto sp=make_shared<string>("tsm");

    // 正常方式创建 shared_ptr
    shared_ptr<string> sp(new string("tsm"));

    // 使用 * 访问他的数据
    *sp="tsm1";

    //打印
    cout<< *sp <<endl;

    // 使用 -> 调用对象方法
    sp->replace(0,1,"T");

    //打印
    cout<< *sp <<endl;

    // 简写方式
    auto sp2=std::make_shared<string>("ttt");

//    // 错误 简写时不能传入一个 new 的对象, 在 make_shared 的过程中会使用 allow 重新申请内存
//    auto sp3=std::make_shared<string>(new string("ttt"));

    // use_count 返回持有该智能指针对象的个数
    cout<< sp2.use_count() <<endl;

    return 0;
}

结果

D:\CWorkSpace\tsmTest\cmake-build-debug\tsmTest.exe
tsm1
Tsm1
1
Process finished with exit code 0
// use_count 返回持有该智能指针对象的个数
cout<< sp2.use_count() <<endl; // 个数为1

// 使用 reset 重新将 sp2 赋值相同类型的对象,注意这里必须是 Object* ,也就是对象指针
sp2.reset(new string("tsm"));

//打印
cout<<*sp2<<endl; //tsm

他的析构函数是根据 use_count() 函数来控制的 为1 则任务没有其他地方引用了,则回收对象的资源,大于 1 则将 used_count 计数减一即可

get 方法返回存储对象的指针地址

// 返回存储的指针
cout<<sp2.get()<<endl;    //0x11c1768