• C++特性之智能指针shared_ptr


    C++特性之智能指针shared_ptr

      shared_ptr 是C++11提供的一种智能指针类,它足够智能,可以在任何地方都不使用时自动删除相关指针,从而帮助彻底消除内存泄漏和悬空指针的问题。
      它遵循共享所有权的概念,即不同的 shared_ptr 对象可以与相同的指针相关联,并在内部使用引用计数机制来实现这一点。

    • 每个 shared_ptr 对象在内部指向两个内存位置:
      1、指向对象的指针。
      2、用于控制引用计数数据的指针。
    • 共享所有权如何在参考计数的帮助下工作:
      1、当新的 shared_ptr 对象与指针关联时,则在其构造函数中,将与此指针关联的引用计数增加1。
      2、当任何 shared_ptr 对象超出作用域时,则在其析构函数中,它将关联指针的引用计数减1。如果引用计数变为0,则表示没有其他 shared_ptr 对象与此内存关联,在这种情况下,它使用delete函数删除该内存。

    1.创建指针对象

    • 使用原始指针创建 shared_ptr 对象
    std::shared_ptr<int> p1(new int());
    
    //检查shared_ptr对象的引用计数
    p1.use_count();
    
    • 1
    • 2
    • 3
    • 4

    上面这行代码在堆上创建了两块内存:1:存储int。2:用于引用计数的内存,管理附加此内存的 shared_ptr 对象的计数,最初计数将为1。
    for ex:

    #include 
    #include 
    
    struct C {int* data;};
    
    int main () {
     auto deleter = [](int*p){
        std::cout << "[deleter called]\n"; delete p;
      };//Labmbda表达式
    
      std::shared_ptr<int> p1;//默认构造,没有获取任何指针的所有权,引用计数为0
      std::shared_ptr<int> p2 (nullptr);//同1
      std::shared_ptr<int> p3 (new int);//拥有指向int的指针所有权,引用计数为1
      std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是拥有自己的析构方法,如果指针所指向对象为复杂结构C
                                        //结构C里有指针,默认析构函数不会将结构C里的指针data所指向的内存释放,这时需要自己使用自己的析构函数(删除器)
      std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但拥有自己的分配器(构造函数),如成员中有指针,可以为指针分配内存,原理跟浅拷贝和深拷贝类似
      std::shared_ptr<int> p6 (p5);//如果p5引用计数不为0,则引用计数加1,否则同样为0
      std::shared_ptr<int> p7 (std::move(p6));//获取p6的引用计数,p6引用计数为0
      std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));//p8获取所有权,引用计数设置为1
      std::shared_ptr<C> obj (new C);
      std::shared_ptr<int> p9 (obj, obj->data);//同6一样,只不过拥有自己的删除器与4一样
    
      std::cout << "use_count:\n";
      std::cout << "p1: " << p1.use_count() << '\n';
      std::cout << "p2: " << p2.use_count() << '\n';
      std::cout << "p3: " << p3.use_count() << '\n';
      std::cout << "p4: " << p4.use_count() << '\n';
      std::cout << "p5: " << p5.use_count() << '\n';
      std::cout << "p6: " << p6.use_count() << '\n';
      std::cout << "p7: " << p7.use_count() << '\n';
      std::cout << "p8: " << p8.use_count() << '\n';
      std::cout << "p9: " << p9.use_count() << '\n';
      return 0;
    }
    /*
    Output:
    use_count:
    p1: 0
    p2: 0
    p3: 1
    p4: 1
    p5: 2
    p6: 0
    p7: 2
    p8: 1
    p9: 2
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 创建空的 shared_ptr 对象,因为带有参数的 shared_ptr 构造函数是 explicit 类型的,所以不能像这样std::shared_ptr p1 = new int();隐式调用它构造函数。创建新的shared_ptr对象的最佳方法是使用std :: make_shared:
    std::shared_ptr<int> p1 = std::make_shared<int>();
    
    • 1

    std::make_shared 一次性为int对象和用于引用计数的数据都分配了内存,而new操作符只是为int分配了内存。

    • 赋值:
    #include 
    #include 
    
    int main () {
      std::shared_ptr<int> foo;
      std::shared_ptr<int> bar (new int(10));
    
      foo = bar;                          // 拷贝,引用计数加1
    
      bar = std::make_shared<int> (20);   // 移动
    //unique_ptr 不共享它的指针。它无法复制到其他 unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库 (STL) 算法。只能移动unique_ptr
      std::unique_ptr<int> unique (new int(30));
      foo = std::move(unique);            // move from unique_ptr,引用计数转移
    
      std::cout << "*foo: " << *foo << '\n';
      std::cout << "*bar: " << *bar << '\n';
    
      return 0;
    }
    Output:
    /*
    *foo: 30
    *bar: 20
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2.分离关联的原始指针

    要使 shared_ptr 对象取消与相关指针的关联,可以使用reset()函数:

    //不带参数的reset(),将引用计数减少1,如果引用计数变为0,则删除指针
    p1.reset();
    
    //带参数的reset(),他将内部指向新指针,因此其引用计数将再次变为1
    p1.reset(new int(34));
    
    //使用nullptr重置:
    p1=nullptr
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    #include 
    #include   // 需要包含这个头文件
    
    int main()
    {
    	// 使用 make_shared 创建空对象
    	std::shared_ptr<int> p1 = std::make_shared<int>();
    	*p1 = 78;
    	std::cout << "p1 = " << *p1 << std::endl; // 输出78
    
    	// 打印引用个数:1
    	std::cout << "p1 Reference count = " << p1.use_count() << std::endl;
    
    	// 第2个 shared_ptr 对象指向同一个指针
    	std::shared_ptr<int> p2(p1);
    
    	// 下面两个输出都是:2
    	std::cout << "p2 Reference count = " << p2.use_count() << std::endl;
    	std::cout << "p1 Reference count = " << p1.use_count() << std::endl;
    
    	// 比较智能指针,p1 等于 p2
    	if (p1 == p2) {
    		std::cout << "p1 and p2 are pointing to same pointer\n";
    	}
    
    	std::cout<<"Reset p1 "<<std::endl;
    
    	// 无参数调用reset,无关联指针,引用个数为0
    	p1.reset();
    	std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
    	
    	// 带参数调用reset,引用个数为1
    	p1.reset(new int(11));
    	std::cout << "p1  Reference Count = " << p1.use_count() << std::endl;
    
    	// 把对象重置为NULL,引用计数为0
    	p1 = nullptr;
    	std::cout << "p1  Reference Count = " << p1.use_count() << std::endl;
    	if (!p1) {
    		std::cout << "p1 is NULL" << std::endl; // 输出
    	}
    	return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    3.与普通指针比较

    缺少 ++, – – 和 [] 运算符
    与普通指针相比,shared_ptr仅提供-> 、*和==运算符,没有+、-、++、–、[]等运算符。

    #include
    #include
    
    struct Sample {
    	void dummyFunction() {
    		std::cout << "dummyFunction" << std::endl;
    	}
    };
    
    int main()
    {
    
    	std::shared_ptr<Sample> ptr = std::make_shared<Sample>();
    
    	(*ptr).dummyFunction(); // 正常
    	ptr->dummyFunction(); // 正常
    
    	// ptr[0]->dummyFunction(); // 错误方式
    	// ptr++;  // 错误方式
    	//ptr--;  // 错误方式
    
    	std::shared_ptr<Sample> ptr2(ptr);
    	if (ptr == ptr2) // 正常
    		std::cout << "ptr and ptr2 are equal" << std::endl;
    	return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    4.NULL检测

    当我们创建 shared_ptr 对象而不分配任何值时,它就是空的;普通指针不分配空间的时候相当于一个野指针,指向垃圾空间,且无法判断指向的是否是有用数据。

    std::shared_ptr<Sample> ptr3;
    if(!ptr3)
    	std::cout<<"Yes, ptr3 is empty" << std::endl;
    if(ptr3 == NULL)
    	std::cout<<"ptr3 is empty" << std::endl;
    if(ptr3 == nullptr)
    	std::cout<<"ptr3 is empty" << std::endl;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    参考:
    C++ 智能指针 shared_ptr 详解与示例
    std::shared_ptr 详解

  • 相关阅读:
    【云上探索实验室】快速入门AI 编程助手 Amazon CodeWhisperer ——码上学堂领学员招募
    汽车4S集团数据分析
    数据分析技能点-正态分布和其他变量分布
    Chatgpt批量改写文章网页版可多开软件-自动登录换号生成word或者TXT
    hist转xlsx和txt
    GPT状态和原理 - 解密OpenAI模型训练
    linux+ndk把jni制作成so库供apk使用(带线程的回调)
    github-actions
    Linux系统部署PostgreSQL 单机数据库
    Redis 主从复制
  • 原文地址:https://blog.csdn.net/yohnyang/article/details/128118719