shared_ptr 与 unique_ptr 的转换 笔记

推荐B站文章:

6.shared_ptr与unique_ptr_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV18B4y187uL?p=6&vd_source=a934d7fc6f47698a29dac90a922ba5a3我的往期文章:

独占指针:unique_ptr 与 函数调用-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/135841140?spm=1001.2014.3001.5501计数指针:shared_ptr (共享指针)与函数-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/135851596?spm=1001.2014.3001.5501

(1)shared_ptrunique_ptr

  • 不能将shared_ptr 转换为unique_ptr
  • unique_ptr可以转换为shared_ptr
    • 通过std::move

(2)常见的设计

  • 将你的函数返回unique_ptr是一种常见的设计模式,这样可以提高代码的复用度,你可以随时改变为shared_ptr
  • 因为返回unique_ptr类型的可以直接赋值给shared_ptr类型的
cpp 复制代码
#include <iostream>
#include <memory>
#include "cat.h"
using namespace std;

std::unique_ptr<Cat> get_unique_ptr() { 
    std::unique_ptr<Cat> cat_p = std::make_unique<Cat>("lanmao");
    return cat_p;
}

int main(int argc,char* argv[]) {
    std::unique_ptr<Cat> c_p_1 = std::make_unique<Cat>("TomCat");
    std::shared_ptr<Cat> c_p_2 = std::move(c_p_1);// 将unique_ptr转换成shared_ptr
    cout<<"c_p_2 use count : " << c_p_2.use_count() << endl;// 1
    
    // func
    std::shared_ptr<Cat> c_p_3 = get_unique_ptr();
    if(c_p_3) {
        c_p_3->catInfo();
        cout<<"c_p_3 use count : " << c_p_3.use_count() << endl; // 输出1
    }
    cout<<"over~"<<endl;
    return 0;
}

执行结果:

cpp 复制代码
PS D:\Work\C++UserLesson\cppenv\bin\Debug> ."D:/Work/C++UserLesson/cppenv/bin/Debug/app.exe"
Constructor of Cat : TomCat
c_p_2 use count : 1
Constructor of Cat : lanmao
cat info name : lanmao
c_p_3 use count : 1
over~
Destructor of Cat
Destructor of Cat
PS D:\Work\C++UserLesson\cppenv\bin\Debug>
相关推荐
SuperHeroWu712 天前
【HarmonyOS NEXT】systemDateTime 时间戳转换为时间格式 Date,DateTimeFormat
harmonyos·时间戳·date·转换·systemdatetime·datetimeformat·时间格式
SunkingYang20 天前
C#如何通过使用XpsToPdf库来转换xps为pdf文件
pdf·c#·使用方法·转换·xps·xpstopdf
SunkingYang25 天前
如何将xps文件转换为txt文件?xps转为pdf,pdf转为txt,提取pdf表格并转为txt
pdf·c#·解析·csv·转换·txt·xps
SunkingYang1 个月前
如何将原来使用cmakelist编译的qt工程转换为可使用Visual Studio编译的项目
qt·编译·cmake·visual studio·转换·cmakelist·sln
winfredzhang2 个月前
从 PDF 到 Word:一个简单的 PythonGUI转换器
python·pdf·word·转换
caz282 个月前
rpm包转deb包或deb包转rpm包
rpm·转换·deb·alien
哈市雪花3 个月前
图形几何之美系列:仿射变换矩阵之Y-Up和Z-Up
线性代数·矩阵·转换·空间变换·y up·z up
许野平3 个月前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
梦想患者4 个月前
浅谈智能指针工作原理(std::shared_ptr、std::unique_ptr、std::weak_ptr、std::auto_ptr)
开发语言·c++·智能指针·unique_ptr·shared_ptr·weak_ptr
这是我586 个月前
C语言阴阳迷宫
c语言·其他·游戏·visual studio·转换·迷宫·阴阳