计数指针 std::shared_ptr

news2024/9/27 5:59:34

shared_ptr 共享指针

  • shared_ptr 计数指针称为共享指针,可以共享数据。
  • shared_ptr 创建了一个计数器与类对象所指的内存相关联
  • Copy 之后计数器加一,销毁之后计数器减一。
  • 计数器 API 接口为 :use_count()

测试代码:

#include <iostream>
#include <memory>

class Stu {
    
    std::string m_name;

public:
    Stu() {
        this->m_name = "stuTemp";
        std::cout << "无参构造" << std::endl;
    }
    Stu(std::string name) :m_name(name) {
        std::cout << "有参构造" << std::endl;
    }
    ~Stu() {
        std::cout << "析构" << std::endl;
    }

    void printStuName() const {
        std::cout << this->m_name << std::endl;
    }
};

int main() {

    // 常量类型
    std::shared_ptr<int> i_p1 = std::make_shared<int>(10);
    std::cout << "value:" << *i_p1 << std::endl;
    std::cout << "use count:" << i_p1.use_count() << std::endl;

    std::shared_ptr<int> i_p2 = i_p1;
    std::cout << "i_p1 use count:" << i_p1.use_count() << std::endl;
    std::cout << "i_p2 use count:" << i_p2.use_count() << std::endl;

    *i_p1 = 20;
    std::cout << "i_p1 value:" << *i_p1 << std::endl;
    std::cout << "i_p2 value:" << *i_p2 << std::endl;

    //i_p1 = nullptr;
    i_p2 = nullptr;
    std::cout << "i_p1 use count:" << i_p1.use_count() << std::endl;
    std::cout << "i_p2 use count:" << i_p2.use_count() << std::endl;

    // 自定义类型
    std::shared_ptr<Stu> s_p1 = std::make_shared<Stu>("FF");
    std::cout << "s_p1 use count:" << s_p1.use_count() << std::endl;
    std::shared_ptr<Stu> s_p2 = s_p1;
    std::shared_ptr<Stu> s_p3 = s_p1;
    std::cout << "s_p1 use count:" << s_p1.use_count() << std::endl;
    std::cout << "s_p2 use count:" << s_p2.use_count() << std::endl;
    std::cout << "s_p3 use count:" << s_p3.use_count() << std::endl;

    s_p1.reset(); // 只有清空的是 0
    std::cout << "s_p1 use count:" << s_p1.use_count() << std::endl;
    std::cout << "s_p2 use count:" << s_p2.use_count() << std::endl;
    std::cout << "s_p3 use count:" << s_p3.use_count() << std::endl;

    return 0;
}

运行结果:

被销毁的指针 use_count 被清零 


 shared_ptr 与 函数调用

传入值的方式:

  • copy的方式
  • 函数内部计数器加一

传入引用的方式:

  • const 限制传入其指向

函数返回值的方式:

  • 链式调用

测试代码: 

#include <iostream>
#include <memory>

class Stu {
    
    std::string m_name;

public:
    Stu() {
        this->m_name = "stuTemp";
        std::cout << "无参构造" << std::endl;
    }
    Stu(std::string name) :m_name(name) {
        std::cout << "有参构造" << std::endl;
    }
    ~Stu() {
        std::cout << "析构" << std::endl;
    }

    void printStuName() const {
        std::cout << this->m_name << std::endl;
    }

    void setStuName(std::string name) {
        this->m_name = name;
    }
};

void doWithPassValue(std::shared_ptr<Stu> s) {
    s->setStuName("aa");
    s->printStuName(); // aa
    std::cout << "value s use count:" << s.use_count() << std::endl; // 2
}

void doWithPassRef(const std::shared_ptr<Stu>& s) {
    s->setStuName("bb");
    s->printStuName(); // bb
    std::cout << "reference s use count" << s.use_count() << std::endl; // 1
}

std::shared_ptr<Stu> doWithPassReturn(const std::string str) {
    std::shared_ptr<Stu> s = std::make_shared<Stu>(str);
    return s;
}

int main() {

    // 1、by value
    std::shared_ptr<Stu> s_p1 = std::make_shared<Stu>("AA");
    doWithPassValue(s_p1);
    s_p1->printStuName(); // aa
    std::cout << "s_p1 use count:" << s_p1.use_count() << std::endl; // 1

    // 2、by reference
    std::shared_ptr<Stu> s_p2 = std::make_shared<Stu>("BB");
    doWithPassRef(s_p2);
    s_p2->printStuName(); // bb
    std::cout << "s_p2 use count:" << s_p2.use_count() << std::endl; // 1

    // 3、by return value
    //doWithPassReturn("CC")->printStuName();
    std::shared_ptr<Stu> s_p3 = doWithPassReturn("CC");
    s_p3->printStuName();
    std::cout << "s_p3 use count:" << s_p3.use_count() << std::endl; // 1


    std::cout << "-----------" << std::endl;

    return 0;
}

运行结果:


shared_ptr 与 unique_ptr 

  • shared_ptr 不可以转换为 unique_ptr。
  • unique_ptr 可以通过 move 的方法 转化为 shared_ptr。
  • 函数返回值可以设计为 返回 unique_ptr 类型,unique_ptr 可以转化为 shared_ptr。提高代码复用度,随时更改为 shared_ptr。

测试代码: 

#include <iostream>
#include <memory>

class Stu {
    
    std::string m_name;

public:
    Stu() {
        this->m_name = "stuTemp";
        std::cout << "无参构造" << std::endl;
    }
    Stu(std::string name) :m_name(name) {
        std::cout << "有参构造" << std::endl;
    }
    ~Stu() {
        std::cout << "析构" << std::endl;
    }

    void printStuName() const {
        std::cout << this->m_name << std::endl;
    }

    void setStuName(std::string name) {
        this->m_name = name;
    }
};

std::unique_ptr<Stu> getUniquePtr() {
    std::unique_ptr<Stu> s = std::make_unique<Stu>("AA");
    return s;
}

int main() {

    // move 方法
    std::unique_ptr<Stu> u_p1 = std::make_unique<Stu>("FF");
    std::shared_ptr<Stu> s_p1 = std::move(u_p1); // 转移所有权

    std::cout << s_p1.use_count() << std::endl;


    // function return
    // 返回 unique_ptr 接受可以使用 shared_ptr
    std::shared_ptr<Stu> s_p2 = getUniquePtr();
    if (s_p2) {
        s_p2->printStuName();
        std::cout << "s_p2 use count:" << s_p2.use_count() << std::endl;
    }
    return 0;
}

运行结果:

unique_ptr 在使用上是很方便的,用作函数返回值可以用 shared_ptr 去接受,也可以通过 move 方法将所有权转换到 shared_ptr 上,原本的 unique_ptr 经过转移就不可以再使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/131148.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python + Django开发在线考试管理系统(附源码)

本文最终实现一个Web在线考试管理系统&#xff0c;可作为Python Web&#xff0c;Django的练手项目&#xff0c;也可以作为计算机毕业设计参考项目。 文章目录系统功能需求分析系统设计及实现思路源码分享&系统实现过程系统展示系统功能需求分析 在线考试管理系统&#xff…

机器学习中的数学原理——二分类问题

今天是2022年的最后一天&#xff0c;提前祝大家新年快乐&#xff01;这个专栏主要是用来分享一下我在机器学习中的学习笔记及一些感悟&#xff0c;也希望对你的学习有帮助哦&#xff01;感兴趣的小伙伴欢迎私信或者评论区留言&#xff01;这一篇就更新一下《白话机器学习中的数…

shell流程控制之条件判断练习

1、ping主机测试,查看主机是否存活&#xff1b; #!/bin/bash ######################### #File name:ping.sh #Version:v1.0 #Email:admintest.com #Created time:2022-12-28 05:06:21 #Description: ######################### var$( ifconfig ens33 | grep inet | grep -v…

【JavaSE成神之路】Java面向对象(下)

哈喽&#xff0c;我是兔哥呀&#xff0c;今天就让我们继续这个JavaSE成神之路&#xff01; 这一节啊&#xff0c;咱们要学习的内容还是Java的面向对象。 1. 构造方法 构造方法和new关键字是一对好拍档。 在之前GirlFriend的例子中&#xff0c;我们写了两个构造方法&#xff…

gl inet mt1300读写性能测试

为什么买这个路由器 1.最近需要一个路由器, 2.我需要在局域网存储一些东西方便手机电脑访问(微型nas), 3.另外还希望这个路由器是开源智能路由器(能装插件玩), 4.小,非常小,typec 供电(5v 1.5A),非常方便,支持tf卡 usb3.0 wifi 5GHz (1)不用nas的原因:我只是轻度使用nas,专…

Fedora 装系统后连接不上无线网络和蓝牙设备

Fedora 装系统后连接不上蓝牙鼠标0.升级系统&#xff0c;升级后仍然无法使用&#xff0c;执行步骤1-3的方法。1.查看本机是否有无线硬件模块——有2. 查看本机是否有蓝牙固件【驱动】——无3. 安装无线网络驱动3.1 打开终端3.2 安装dnf并配置3.3 使用dnf安装kmod-wl&#xff0c…

钉钉6亿用户的哲学:产业互联网的海洋里,没有人是一座孤岛

除了拥有大人口和大市场条件的中国&#xff0c;或许难有另一个国家再现数亿人共同投身产业互联网的场景。除了钉钉&#xff0c;或许也很难有别的软件能同时承载6亿人的数字化理想。 12月28日&#xff0c;钉钉总裁叶军在2022钉钉7.0产品发布会上&#xff0c;带来了钉钉的最新数…

知识变现海哥:如何将你的知识变成一套解决方案

知识变现海哥&#xff1a;如何将你的知识变成一套解决方案 之前我说过我们卖的不是自己能力&#xff0c;而是一套成体系的解决方案&#xff0c;因为没有人会单纯地为能力买单&#xff0c;我们越是能证明自己的能力有价值&#xff0c;就越能将自己的能力卖高价。而价值要怎么证…

Acwing---789.数的范围

数的范围1.题目2.基本思想3.代码实现4.总结1.题目 给定一个按照升序排列的长度为n的整数数组&#xff0c;以及 q 个查询。 对于每个查询&#xff0c;返回一个元素k的起始位置和终止位置&#xff08;位置从0开始计数&#xff09;。 如果数组中不存在该元素&#xff0c;则返回“…

使用递归和非递归方式实现二叉树先序、中序、后序遍历

题目&#xff1a; 用递归和非递归方式&#xff0c;分别按照二叉树先序、中序和后续打印所有的节点。先序为根左右&#xff0c;中序为左根右&#xff0c;后序为左右根。 递归方式&#xff1a; &#xff08;1&#xff09;先序&#xff1a; //先序 根左右public static void pr…

TypeScript入门

这两天终于抽空学习了typescript&#xff0c;把欠了四年的帐给补上了。 废话不多说&#xff0c;先上官网链接&#xff1a;TypeScript中文网 TypeScript——JavaScript的超集 一、下载安装&#xff1a;用npm > npm install -g typescript 验证是否安装成功&#xff1a; …

保存网页内容 自动过滤广告和网页头尾

网页可以非常方便的为我们展示各种信息&#xff0c;如果遇到重要的资料文献&#xff0c;希望在本地电脑上保存下来该怎么操作呢&#xff1f;把网址添加到收藏夹&#xff0c;下次直接打开网址查看&#xff0c;但如果资源被网站删除&#xff0c;就再也找不到了。还是保存在自己电…

msf联动cs

Cobalt Strike简称CS 用于团队作战使用&#xff0c;由一个服务端和多个客户端组成&#xff0c;能让多个攻击者这在一个团队服务器上共享目标资源和信息&#xff0c;我们在使用msf获得权限以后&#xff0c;可以将信息共享到cs上&#xff0c;使用cs来进行监听以及其他的操作。 1…

理解Kotlin泛型

文章目录Kotlin泛型声明处型变协变< out T>逆变< in T>使用处型变(类型投影)参考Kotlin泛型 声明处型变 协变< out T> interface GenericsP<T> {fun get(): T //读取并返回T&#xff0c;可以认为只能读取T的对象是生产者 }如上声明了GenericsP<…

【C++】STL —— 用哈希表同时封装出unordered_set和unordered_map

目录 一、底层结构 1. 哈希的概念 二、哈希冲突 三、哈希函数 四、解决哈希冲突 1. 闭散列&#xff08;开放定址法&#xff09; 1. 线性探测 2. 二次探测 2. 闭散列的实现 3. 开散列&#xff08;拉链法&#xff09; 4. 开散列和闭散列的比较 五、HashTable的…

树莓派内核编译

文章参考&#xff1a; 深海游弋的鱼 – 默默的点滴 (mobibrw.com) 深海游弋的鱼 – 默默的点滴 (mobibrw.com) 1. 安装 git sudo apt install git 2. 下载树莓派内核源码 git clone --depth1 -b rpi-4.9.y https://github.com/raspberrypi/linux.git rpi-linux 3. 安装…

Python采集wangyi财经数据信息,做个可视化小案例

前言 2022年全球股市普跌&#xff0c;你亏了多少钱&#xff1f; 亏多少我也不知道&#xff0c;我只是想着来采集数据&#xff0c;做个可视化小案例来玩玩 话不多说&#xff0c;咱就直接开始吧 开发环境 解释器版本: python 3.8代码编辑器: pycharm 2021.2requests: pip ins…

Python笔记 | 卡布列克常数

0x00 前言 任意一个不是由完全相同数字组成的四位数&#xff0c;如果对它们的每位数字重新排序&#xff0c;组成一个较大的数和一个较小的数&#xff0c;然后用较大数减去较小数&#xff0c;差不够四位数时补零&#xff0c;类推下去&#xff0c;最后将变成一个固定的数&#xf…

使用kubeadm安装kubernetes记录

1.查看版本信息 # 在 master 节点和 worker 节点都要执行 cat /etc/redhat-release# 此处 hostname 的输出将会是该机器在 Kubernetes 集群中的节点名字 # 不能使用 localhost 作为节点的名字 hostname# 请使用 lscpu 命令&#xff0c;核对 CPU 信息 # Architecture: x86_64 …

C语言指针全解

C语言指针全解指针的定义指针的大小指针类型指针类型意义野指针二级指针字符指针指针数组数组指针&数组名 VS 数组名应用数组参数、指针参数函数指针函数指针数组函数指针数组的使用 - 模拟计算器指向函数指针数组的指针回调函数回调函数的使用 - qsort函数指针的定义 在计…