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>
相关推荐
这是我581 个月前
C语言阴阳迷宫
c语言·其他·游戏·visual studio·转换·迷宫·阴阳
ONLYOFFICE2 个月前
如何在Linux系统上使用ONLYOFFICE文档编辑PDF文件
linux·pdf·开源·开源软件·工具·转换·转换器
老狼88484 个月前
用WPS将多张图片生成一个pdf文档,注意参数设置
pdf·转换·多图
fyhs5 个月前
Python读取ASC文件并转换成Excel文件(坐标)
python·转换
fyhs5 个月前
Python实现txt转Excel(坐标)
python·转换
ONLYOFFICE6 个月前
使用 ONLYOFFICE API 构建 Java 转换器,在 Word 和 PDF 之间进行转换
java·pdf·word·onlyoffice·转换
江湖上都叫我秋博7 个月前
传感器_雷达坐标系到转台坐标系的转换
雷达·传感器·转换·坐标系·转台
弗锐土豆7 个月前
吐槽FineDataLink工具Format函数处理日期转字符串格式的说明文档
时间·格式·转换·format·finedatalink
SunkingYang7 个月前
MFC中字符串string类型和CString类型互转方法
mfc·string·方法·转换·cstring·互转