智能指针
来源:互联网 发布:黑米软件怎么安装 编辑:程序博客网 时间:2024/05/17 04:51
智能指针
new, share_ptr指针类型的基本初始化和使用.
share_ptr : 编译器自动的释放内存, 不需要手动delete;
new : 我们需要手动的释放内存(delete);
#include <iostream>#include <cstdlib>#include <memory>#include <string>#include <new>int main(){ //new : 初始化, 建议使用new int(); 直接初始化; int *a1 = new int; int *a2 = new int(); int *a3 = new (std::nothrow) int(); //nothrow 分配空间失败时会自动将 a3 变为空指针而不是编译报错; int *a = new int[20](); //new : 分配一个数组; delete[] a; //销毁数组, 要加 [] ; delete a1; delete a2; delete a3; //shared_ptr : 智能指针的初始化; 系统自动释放内存; //shared_ptr : 不支持管理动态数组; //unique_ptr, weak_ptr暂未了解; std::shared_ptr<std::string> p1 = std::make_shared<std::string >("adsd"); std::cout << *p1 << "\n"; std::shared_ptr<std::string > p2 = std::make_shared<std::string >(10, 'a'); std::cout << *p2 << "\n"; std::shared_ptr<int > p3(new (std::nothrow) int(29)); std::cout << *p3 << "\n"; //shared_ptr : 不支持管理动态数组; //智能用lambda做为删除器执行释放数组[]; //对其赋值和遍历只能用 p.get() 以及下标运算符; std::shared_ptr<int> p4(new (std::nothrow) int[10], [](int *p4) { delete p4; }); for (size_t i = 0; i < 10; i++) *(p4.get() + i) = i; for (size_t i = 0; i < 10; i++) std::cout << *(p4.get() + i) << " "; system("pause"); return 0;}
自我感觉share_ptr好处很好, 弊端也大, 动态数组创建太麻烦了.
阅读全文
0 0
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- 智能指针
- PAT1078 Hashing 坑爹
- 剑指Offer:链表中环的入口结点
- python重点语法总结(三)----*和**的作用
- Delphi.NET 开发有哪些优势?
- Quartz调度器
- 智能指针
- Struts2 Annotation 注解配置
- 虚拟机下ubuntu与主机WinSCP配置
- Unity 动画知识之一
- 20170804工作记账流水(2017-08-04 10:00)
- vue 2.0系列QQ音乐播放器案例
- volatile
- unity动态加载Animator的Controller
- java进行字符串与字符串或者字符串与数字进行加减乘除四则运算