智能指针2:不带引用计数的智能指针(auto_ptr、unique_ptr)

不带引用计数的智能指针

智能指针的出发点是管理堆对象,是那些不会自动释放资源的。

1、auto_ptr(C++11抛弃)

  • 底层只有裸指针,独占式的,永远只让最后一个指针管理资源,只有普通的拷贝构造和赋值重载

  • 基本使用:

    cpp 复制代码
    #include<iostream>
    #include<memory>
    using namespace std;
    int main(){
     auto_ptr<int> ptr1(new int);
     auto_ptr<int> ptr2(ptr1); 
     //先把ptr1底层的值记下来,再将ptr1=null,后
     // 面将记下来的值return给ptr2
     *ptr2 = 20;
     cout << *ptr1 << endl; // 程序崩溃,ptr1已经是空指针了 
     return 0;
    }
  • 上面的底层逻辑:

    cpp 复制代码
    //构造函数
    auto_ptr(auto_ptr& _Right) noexcept : _Myptr(_Right.release()) {}
    //release的实现
    _Ty* release() noexcept {
    	  _Ty* _Tmp = _Myptr;
           _Myptr = nullptr;
           return _Tmp;
      }
  • 初始化:

    cpp 复制代码
    #include <memory>
    
    int main()
    {
        //初始化方式1
        std::auto_ptr<int> sp1(new int(8));
        //初始化方式2
        std::auto_ptr<int> sp2;
        sp2.reset(new int(8));
    
        return 0;
    }
    /*
    void reset(_Ty* _Ptr = nullptr) noexcept {
            if (_Ptr != _Myptr) {
                delete _Myptr;
            }
            _Myptr = _Ptr;
      }
    */
  • TIP:

    • 不推荐使用,可以简单的使用,不适合复杂场景
    • 可以在容器里面使用auto_ptr吗? 不建议使用,容器底部的资源会被转移,采用的拷贝构造,明眼看不出来

2、unique_ptr

  • 删除普通的拷贝构造和赋值重载,提供移动构造和移动赋值重载相比于auto_ptr将资源的转移摆在了明面上

    cpp 复制代码
     unique_ptr(const unique_ptr&)            = delete;
     unique_ptr& operator=(const unique_ptr&) = delete;
     // 提供了右值版本
     unique_ptr(unique_ptr&& _Right);
     unique_ptr& operator=(unique_ptr&& _Right);
  • 初始化:

    cpp 复制代码
    //初始化方式1
    std::unique_ptr<int> sp1(new int(123));
    
    //初始化方式2
    std::unique_ptr<int> sp2;
    sp2.reset(new int(123));
    
    //初始化方式3,这个方法更安全,但是C++14才出来
    std::unique_ptr<int> sp3 = std::make_unique<int>(123);
  • 基本使用:

    cpp 复制代码
    #include<iostream>
    #include<memory>
    using namespace std;
    int main()
    {
    	unique_ptr<int> p1(new int);
    	// unique_ptr<int> p2(p1);  //直接传入左值会报错
    	//不能调用,会报错 attempting to reference a deleted function
    	unique_ptr<int> p2(std::move(p1)); //先将p1转换为右值,再拷贝给p2
    }
  • TIP:

    • 由于右值拷贝和右值赋值重载的存在,uniuqe_ptr可以用于函数调用过程中
相关推荐
SuperCandyXu27 分钟前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
愈努力俞幸运1 小时前
c++ 头文件
开发语言·c++
~山有木兮1 小时前
C++设计模式 - 单例模式
c++·单例模式·设计模式
十五年专注C++开发2 小时前
CMake基础:gcc/g++编译选项详解
开发语言·c++·gcc·g++
HUN金克斯2 小时前
C++/C函数
c语言·开发语言·c++
慢半拍iii2 小时前
数据结构——F/图
c语言·开发语言·数据结构·c++
iceslime3 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
虾球xz3 小时前
CppCon 2015 学习:3D Face Tracking and Reconstruction using Modern C++
开发语言·c++·学习·3d
small_wh1te_coder4 小时前
c语言超详细知识点总结 1500行手写源码 持续更新中ing 从25年5月到6月5日
c++·c
SteveDraw6 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库