【校招面试 之 C/C++】第26题 C++ 智能指针(二)之 share_ptr
1、综述
shared_ptr 是一个标准的共享所有权的智能指针, 允许多个指针指向同一个对象. 定义在 memory 文件中(非memory.h), 命名空间为 std.
shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针, 当然这需要额外的开销:
(1) shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针.
(2) 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样.
(3) 开销并不是我们不使用shared_ptr的理由, 永远不要进行不成熟的优化, 直到性能分析器告诉你这一点.
使用方法:
可以使用模板函数 make_shared 创建对象, make_shared 需指定类型('<>'中)及参数('()'内), 传递的参数必须与指定的类型的构造函数匹配. 如:
std::shared_ptr<int> sp1 = std::make_shared<int>(10);
std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");
也可以定义 auto 类型的变量来保存 make_shared 的结果.
auto sp3 = std::make_shared<int>(11);
printf("sp3=%d\n", *sp3);
auto sp4 = std::make_shared<std::string>("C++11");
printf("sp4=%s\n", (*sp4).c_str());
2、成员函数
use_count 返回引用计数的个数
unique 返回是否是独占所有权( use_count 为 1)
swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr<int> sp(new int(1)); sp 与 sp.get()是等价的
以下代码演示各个函数的用法与特点:
std::shared_ptr<int> sp0(new int(2));
std::shared_ptr<int> sp1(new int(11));
std::shared_ptr<int> sp2 = sp1;
printf("%d\n", *sp0); // 2
printf("%d\n", *sp1); // 11
printf("%d\n", *sp2); // 11
sp1.swap(sp0);
printf("%d\n", *sp0); // 11
printf("%d\n", *sp1); // 2
printf("%d\n", *sp2); // 11 std::shared_ptr<int> sp3(new int(22));
std::shared_ptr<int> sp4 = sp3;
printf("%d\n", *sp3); // 22
printf("%d\n", *sp4); // 22
sp3.reset();
printf("%d\n", sp3.use_count()); // 0
printf("%d\n", sp4.use_count()); // 1
printf("%d\n", sp3); // 0
printf("%d\n", sp4); // 指向所拥有对象的地址 std::shared_ptr<int> sp5(new int(22));
std::shared_ptr<int> sp6 = sp5;
std::shared_ptr<int> sp7 = sp5;
printf("%d\n", *sp5); // 22
printf("%d\n", *sp6); // 22
printf("%d\n", *sp7); // 22
printf("%d\n", sp5.use_count()); // 3
printf("%d\n", sp6.use_count()); // 3
printf("%d\n", sp7.use_count()); // 3
sp5.reset(new int(33));
printf("%d\n", sp5.use_count()); // 1
printf("%d\n", sp6.use_count()); // 2
printf("%d\n", sp7.use_count()); // 2
printf("%d\n", *sp5); // 33
printf("%d\n", *sp6); // 22
printf("%d\n", *sp7); // 22
std::shared_ptr<int> sp1 = std::make_shared<int>(10);
std::shared_ptr<int> sp2 = std::make_shared<int>(11);
auto sp3 = sp2; 或 auto sp3(sp2);
printf("sp1.use_count = %d\n", sp1.use_count()); // 1
printf("sp2.use_count = %d\n", sp2.use_count()); // 2
printf("sp3.use_count = %d\n", sp3.use_count()); // 2
sp3 = sp1;
printf("sp1.use_count = %d\n", sp1.use_count()); // 2
printf("sp2.use_count = %d\n", sp2.use_count()); // 1
printf("sp3.use_count = %d\n", sp3.use_count()); // 2
3、什么时候需要使用share_ptr
(1) 程序不知道自己需要使用多少对象. 如使用窗口类, 使用 shared_ptr 为了让多个对象能共享相同的底层数据.
(2) 程序不知道所需对象的准确类型.
(3) 程序需要在多个对象间共享数据.
4、使用share_ptr的注意事项:
(1) 禁止纯指针给智能指针赋值或者拷贝构造。
int* a=new int(2);
shared_ptr<int>sp=a;// error
sp=a;// error
(2)shared_ptr多次引用同一数据,会导致两次释放同一内存。如下:
{
int* pInt = new int[100];
shared_ptr<int> sp1(pInt);
// 一些其它代码之后…
shared_ptr<int> sp2(pInt);
}
(3)使用share_ptr造成循环引用
#include<iostream>
using namespace std; struct Node
{
shared_ptr<Node> _pre;
shared_ptr<Node> _next; ~Node()
{
cout << "~Node():" << this << endl;
}
int data;
}; void FunTest()
{
shared_ptr<Node> Node1(new Node);
shared_ptr<Node> Node2(new Node);
Node1->_next = Node2;
Node2->_pre = Node1; cout << "Node1.use_count:"<<Node1.use_count() << endl; // 2
cout << "Node2.use_count:"<< Node2.use_count() << endl; //2
} int main()
{
FunTest();
system("pause");
return 0;
}
当出现上述问题时,有以下3种解决方法:
1️⃣当只剩下最后一个引用的时候需要手动打破循环引用释放对象。
2️⃣当parent的生存期超过children的生存期的时候,children改为使用一个普通指针指向parent。
3️⃣使用弱引用的智能指针(weak_ptr)打破这种循环引用。虽然这三种方法都可行,但方法1和方法2都需要程序员手动控制。
关于weak_ptr在下一篇文章中讲到。
参考:https://blog.csdn.net/man_sion/article/details/77196766
【校招面试 之 C/C++】第26题 C++ 智能指针(二)之 share_ptr的更多相关文章
- 【校招面试 之 网络】第3题 HTTP请求行、请求头、请求体详解
1.HTTP请求报文解剖 HTTP请求报文由3部分组成(请求行+请求头+请求体): 下面是一个实际的请求报文: ①是请求方法,GET和POST是最常见的HTTP方法,除此以外还包括DELETE.HEA ...
- 【校招面试 之 网络】第2题 TCP的可靠传输、流量控制、滑动窗口
1.可靠传输 (1)三次握手 TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接: (1)第一次握手:建立连接时,客户端A发送SYN包(SYN=j)到服务器B,并进入SYN_S ...
- 【校招面试 之 C/C++】第27题 C++ 智能指针(三)之 unique_ptr
auto_ptr<string> p1(new string ("auto") : //#1 auto_ptr<string> p2; //#2 p2 = ...
- 【校招面试 之 C/C++】第25题 C++ 智能指针(一)之 auto_ptr
1.智能指针背后的设计思想 我们先来看一个简单的例子: void remodel(std::string & str) { std::string * ps = new std::string ...
- 【校招面试 之 网络】第1题 TCP和UDP
TCP UDP1.TCP与UDP基本区别 (1)基于连接与无连接 (2)TCP要求系统资源较多,UDP较少: (3)UDP程序结构较简单(头只有8个字节:源端口号.目标端口号.长度.差错) ...
- 剑指offer 面试26题
面试26题: 题目:树的子结构 题:输入两棵二叉树A和B,判断B是不是A的子结构. 解题思路:递归,注意空指针的情况. 解题代码: # -*- coding:utf-8 -*- # class Tre ...
- 记2016腾讯 TST 校招面试经历,电面、笔试写代码、技术面、hr面,共5轮
(出处:http://www.cnblogs.com/linguanh/) 前序: 距离 2016 腾讯 TST 校招面试结束已经5天了,3月27日至今,目前还在等待消息.从投简历到两轮电面,再到被 ...
- 墙裂推荐!2020Android阿里&腾讯&百度&字节&美团校招面试汇总
基本情况 2021届硕士生,Android开发岗 此文主要是2020年年初春招实习的面试和正式校招面试经验汇总,最终校招拿到了腾讯,百度,美团等offer 主要包括阿里4面,腾讯实习4面和校招4面,字 ...
- WEB前端面试选择题解答(共36题)
第1题 ["1", "2", "3"].map(parseInt) A:["1", "2", &qu ...
随机推荐
- 1065 A+B and C (64bit) (20 分)
1065 A+B and C (64bit) (20 分) Given three integers A, B and C in [−2^63,2^63], you are suppose ...
- 解决Ubuntu下使用命令行subl 打开Sublime text3无法输入中文的问题
cd /opt/sublime_text/ sudo vim sub-fcitx.c 新建文件sub-fcitx.c,建议放在Sublime Text的所在目录下,将下面的代码复制进去 ,参考: ht ...
- 如何下载spring的jar包?
文转载至:https://www.cnblogs.com/yjmyzz/p/3847364.html Spring官网改版后,很多项目的完整zip包下载链接已经隐掉了,虽然Spring旨在引导大家用更 ...
- 《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #16 OOM Killer的运行与结构
HACK #16 OOM Killer的运行与结构(1) 本节介绍OOM Killer的运行与结构. Linux中的Out Of Memory(OOM) Killer功能作为确保内存的最终手段,可以在 ...
- 中国Linux开源镜像站大全
本文来源:各大开源软件.发行版镜像页面. 请注意这是一个总结,如果您自己搭建了一个小型开源镜像,这里并没有.以下列出的是包含大量不同镜像的站点. 具体配置中,我建议您使用大企业 ...
- java 执行shell命令
Runtime.getRuntime().exec http://blog.csdn.net/heyetina/article/details/6555746
- SQL SERVER回滚恢复误操作的数据
在生产数据库做CURD操作时,可能会有执行某条语句误操作的情况发生,针对这个种情况有两点建议: 1. 在SQL SERVER上开启事务确认功能,当执行完语句后确认无误,再提交事务.(开启方法见附件图片 ...
- Kafka 基本原理
Kafka 基本原理 来源:阿凡卢 , www.cnblogs.com/luxiaoxun/p/5492646.html 简介 Apache Kafka是分布式发布-订阅消息系统.它最初由Link ...
- systemctl管理系统配置、服务
systemctl daemon-reload \&& systemctl enable docker \&& systemctl start docker \& ...
- stdio.h头文件中申明的基本函数
调用scanf函数时,需传入变量的地址作为参数,scanf函数会等待标准输入设备(键盘等)输入数据,并且将输入的数据赋值给地址对应的变量. #include<stdio.h> #inclu ...