当前位置:网站首页>shared_ptr 和 make_shared 的使用
shared_ptr 和 make_shared 的使用
2022-07-28 17:40:00 【标biao】
std::shared_ptr
是一种智能指针(本身就是一个对象),指向一个对象。它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显示的调用 delete,当引用计数变为零的时候就会将对象自动删除。
std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过use_count()来查看一个对象的引用计数。
//创建了一个 40字节内存空间 的对象,pointer 指向这个对象
std::shared_ptr pointer = new int(10);
std::shared_ptr pointer2 = pointer; // pointer2 也指向这个对象,且引用计数+1
int *p = pointer.get(); // 这样不会增加引用计数
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3
//创建一个指针ptrB 栈对象,构造函数中没有任何参数,因此默认指向的是null。
std::shared_ptr<int> ptrB();
//这种写法也可以,{}表示赋初值或者说初始化,其它类型变量定义也是如此,是c++11的语法特性
std::shared_ptr<int> ptrB{std::make_shared<int>(5)};注意:std::make_shared不支持数组。
std::make_shared
主要功能是在动态内存中分配一个对象并初始化它,返回指向此对象的shared_ptr。
//p1指向一个值为"9999999999"的string对象
shared_ptr<string> p1 = make_shared<string>(10, '9');
//p2指向一个值为"hello"的string对象
shared_ptr<string> p2 = make_shared<string>("hello");
//p2指向一个为空的string对象
shared_ptr<string> p3 = make_shared<string>();
//这种写法也可以,{}表示赋初值或者说初始化,其它类型变量定义也是如此,是c++11的语法特性
std::shared_ptr<int> ptrB{std::make_shared<int>(5)};
和上面直接使用 new<string>("hello")相比,有什么好处呢:
看下面两张图:内存分配可以一次性完成. 这减少了内存分配的次数, 而内存分配是代价很高的操作.


参考文章:
std::shared_ptr的使用_lyshiba的博客-CSDN博客_shared_ptr使用
边栏推荐
- App自动化测试是怎么实现H5测试的
- 第一次写博客
- How to use Qianqian listening sound effect plug-in (fierce Classic)
- Nips18 (AD) - unsupervised anomaly detection using geometric transformations using geometric augmentation
- 文章翻译软件-批量免费翻译软件支持各大翻译接口
- NDK 系列(5):JNI 从入门到实践,爆肝万字详解!
- Pytorch:快速求得NxN矩阵的主对角线(diagonal)元素与非对角线元素
- Sword finger offer II 109. unlock the password lock
- navicate修改数据库名的方式
- Convertible bond concept table x notation gives you a convenient and fast experience!
猜你喜欢
随机推荐
Srs4.0 installation steps
ES6 conversion of new data type set and arr set map
WPF implements MessageBox message prompt box with mask
After several twists and turns, how long can the TSDB C-bit of influxdb last?
当CNN遇见Transformer《CMT:Convolutional Neural Networks Meet Vision Transformers》
An intern's journey to cnosdb
Share several coding code receiving verification code platforms, which will be updated in February 2022
亚马逊推出Amazon One手掌支付系统,非接触式掌静脉识别市场有望爆发
Adobe XD web design tutorial
Iclr21 (classification) - future classic "vit" an image is worth 16x16 words (including code analysis)
Cvpr19 - adjust reference dry goods bag of tricks for image classification with revolutionary neural network
Jestson nano Object detection
为什么在telnet登入界面下没有日志输出?
R语言与数据分析实战11-数据的删除
Design of library management database system
Mid 2022 summary
SaltStack系统初始化
NDK series (5): from introduction to practice, JNI explodes the liver and explains everything in detail!
C string to short[] method
以数字化转型为契机,3C企业如何通过SRM供应商云协同平台实现高效协同?









