C++中智能指针的原理、使用、实现
C++中智能指针的原理、使用、实现
转自:https://www.cnblogs.com/wxquare/p/4759020.html
1 智能指针的作用
C++程序设计中使用堆内存是非常频繁的操作,堆内存的申请和释放都由程序员自己管理。程序员自己管理堆内存可以提高了程序的效率,但是整体来说堆内存的管理是麻烦的,C++11中引入了智能指针的概念,方便管理堆内存。使用普通指针,容易造成堆内存泄露(忘记释放),二次释放,程序发生异常时内存泄露等问题等,使用智能指针能更好的管理堆内存。
理解智能指针需要从下面三个层次:
从较浅的层面看,智能指针是利用了一种叫做RAII(资源获取即初始化)的技术对普通的指针进行封装,这使得智能指针实质是一个对象,行为表现的却像一个指针。
智能指针的作用是防止忘记调用delete释放内存和程序异常的进入catch块忘记释放内存。另外指针的释放时机也是非常有考究的,多次释放同一个指针会造成程序崩溃,这些都可以通过智能指针来解决。
智能指针还有一个作用是把值语义转换成引用语义。C++和Java有一处最大的区别在于语义不同,在Java里面下列代码:
Animal a = new Animal(); Animal b = a;
你当然知道,这里其实只生成了一个对象,a和b仅仅是把持对象的引用而已。但在C++中不是这样,
Animal a; Animal b = a;
这里却是就是生成了两个对象。关于值语言参考这篇文章http://www.cnblogs.com/Solstice/archive/2011/08/16/2141515.html。
2 智能指针的使用
智能指针在C++11版本之后提供,包含在头文件<memory>
中,shared_ptr
、unique_ptr
、weak_ptr
。
2.1 shared_ptr的使用
shared_ptr多个指针指向相同的对象。shared_ptr使用引用计数,每一个shared_ptr的拷贝都指向相同的内存。每使用他一次,内部的引用计数加1,每析构一次,内部的引用计数减1,减为0时,自动删除所指向的堆内存。shared_ptr内部的引用计数是线程安全的,但是对象的读取需要加锁。
- 初始化。智能指针是个模板类,可以指定类型,传入指针通过构造函数初始化。也可以使用make_shared函数初始化。不能将指针直接赋值给一个智能指针,一个是类,一个是指针。例如std::shared_ptr p4 = new int(1);的写法是错误的
- 拷贝和赋值。拷贝使得对象的引用计数增加1,赋值使得原对象引用计数减1,当计数为0时,自动释放内存。后来指向的对象引用计数加1,指向后来的对象。
- get函数获取原始指针
- 注意不要用一个原始指针初始化多个shared_ptr,否则会造成二次释放同一内存
- 注意避免循环引用,shared_ptr的一个最大的陷阱是循环引用,循环,循环引用会导致堆内存无法正确释放,导致内存泄漏。循环引用在weak_ptr中介绍。
#include <iostream>
#include <memory>int main() {{int a = 10;std::shared_ptr<int> ptra = std::make_shared<int>(a);std::shared_ptr<int> ptra2(ptra); //copystd::cout << ptra.use_count() << std::endl;int b = 20;int *pb = &a;//std::shared_ptr<int> ptrb = pb; //errorstd::shared_ptr<int> ptrb = std::make_shared<int>(b);ptra2 = ptrb; //assignpb = ptrb.get(); //获取原始指针std::cout << ptra.use_count() << std::endl;std::cout << ptrb.use_count() << std::endl;}
}
2.2 unique_ptr的使用
unique_ptr “唯一” 拥有其所指对象,同一时刻只能有一个 unique_ptr 指向给定对象(通过禁止拷贝语义、只有移动语义来实现)。相比与原始指针unique_ptr用于其RAII的特性,使得在出现异常的情况下,动态资源能得到释放。unique_ptr指针本身的生命周期:从unique_ptr指针创建时开始,直到离开作用域。离开作用域时,若其指向对象,则将其所指对象销毁(默认使用delete操作符,用户可指定其他操作)。unique_ptr指针与其所指对象的关系:在智能指针生命周期内,可以改变智能指针所指对象,如创建智能指针时通过构造函数指定、通过reset方法重新指定、通过release方法释放所有权、通过移动语义转移所有权。
#include <iostream>
#include <memory>int main() {{std::unique_ptr<int> uptr(new int(10)); //绑定动态对象//std::unique_ptr<int> uptr2 = uptr; //不能賦值//std::unique_ptr<int> uptr2(uptr); //不能拷貝std::unique_ptr<int> uptr2 = std::move(uptr); //轉換所有權uptr2.release(); //释放所有权}//超過uptr的作用域,內存釋放
}
2.3 weak_ptr的使用
weak_ptr是为了配合shared_ptr而引入的一种智能指针,因为它不具有普通指针的行为,没有重载operator*和->,它的最大作用在于协助shared_ptr工作,像旁观者那样观测资源的使用情况。weak_ptr可以从一个shared_ptr或者另一个weak_ptr对象构造,获得资源的观测权。但weak_ptr没有共享资源,它的构造不会引起指针引用计数的增加。使用weak_ptr的成员函数use_count()可以观测资源的引用计数,另一个成员函数expired()的功能等价于use_count()==0,但更快,表示被观测的资源(也就是shared_ptr的管理的资源)已经不复存在。weak_ptr可以使用一个非常重要的成员函数lock()从被观测的shared_ptr获得一个可用的shared_ptr对象, 从而操作资源。但当expired()==true的时候,lock()函数将返回一个存储空指针的shared_ptr。
#include <iostream>
#include <memory>int main() {{std::shared_ptr<int> sh_ptr = std::make_shared<int>(10);std::cout << sh_ptr.use_count() << std::endl;std::weak_ptr<int> wp(sh_ptr);std::cout << wp.use_count() << std::endl;if(!wp.expired()){std::shared_ptr<int> sh_ptr2 = wp.lock(); //get another shared_ptr*sh_ptr = 100;std::cout << wp.use_count() << std::endl;}}//delete memory
}
2.4 循环引用
考虑一个简单的对象建模——家长与子女:a Parent has a Child, a Child knowshis/her Parent。在Java 里边很好写,不用担心内存泄漏,也不用担心空悬指针,只要正确初始化myChild 和myParent,那么Java 程序员就不用担心出现访问错误。一个handle 是否有效,只需要判断其是否non null。
public class Parent
{private Child myChild;
}
public class Child
{private Parent myParent;
}
在C++ 里边就要为资源管理费一番脑筋。如果使用原始指针作为成员,Child和Parent由谁释放?那么如何保证指针的有效性?如何防止出现空悬指针?这些问题是C++面向对象编程麻烦的问题,现在可以借助smart pointer把对象语义(pointer)转变为值(value)语义,shared_ptr轻松解决生命周期的问题,不必担心空悬指针。但是这个模型存在循环引用的问题,注意其中一个指针应该为weak_ptr。
原始指针的做法,容易出错
#include <iostream> #include <memory>class Child; class Parent;class Parent {private:Child* myChild; public:void setChild(Child* ch) {this->myChild = ch;}void doSomething() {if (this->myChild) {}}~Parent() {delete myChild;} };class Child {private:Parent* myParent; public:void setPartent(Parent* p) {this->myParent = p;}void doSomething() {if (this->myParent) {}}~Child() {delete myParent;} };int main() {{Parent* p = new Parent;Child* c = new Child;p->setChild(c);c->setPartent(p);delete c; //only delete one}return 0; }
循环引用内存泄露的问题
#include <iostream> #include <memory>class Child; class Parent;class Parent {private:std::shared_ptr<Child> ChildPtr; public:void setChild(std::shared_ptr<Child> child) {this->ChildPtr = child;}void doSomething() {if (this->ChildPtr.use_count()) {}}~Parent() {} };class Child {private:std::shared_ptr<Parent> ParentPtr; public:void setPartent(std::shared_ptr<Parent> parent) {this->ParentPtr = parent;}void doSomething() {if (this->ParentPtr.use_count()) {}}~Child() {} };int main() {std::weak_ptr<Parent> wpp;std::weak_ptr<Child> wpc;{std::shared_ptr<Parent> p(new Parent);std::shared_ptr<Child> c(new Child);p->setChild(c);c->setPartent(p);wpp = p;wpc = c;std::cout << p.use_count() << std::endl; // 2std::cout << c.use_count() << std::endl; // 2}std::cout << wpp.use_count() << std::endl; // 1std::cout << wpc.use_count() << std::endl; // 1return 0; }
正确的做法
#include <iostream> #include <memory>class Child; class Parent;class Parent {private://std::shared_ptr<Child> ChildPtr;std::weak_ptr<Child> ChildPtr; public:void setChild(std::shared_ptr<Child> child) {this->ChildPtr = child;}void doSomething() {//new shared_ptrif (this->ChildPtr.lock()) {}}~Parent() {} };class Child {private:std::shared_ptr<Parent> ParentPtr; public:void setPartent(std::shared_ptr<Parent> parent) {this->ParentPtr = parent;}void doSomething() {if (this->ParentPtr.use_count()) {}}~Child() {} };int main() {std::weak_ptr<Parent> wpp;std::weak_ptr<Child> wpc;{std::shared_ptr<Parent> p(new Parent);std::shared_ptr<Child> c(new Child);p->setChild(c);c->setPartent(p);wpp = p;wpc = c;std::cout << p.use_count() << std::endl; // 2std::cout << c.use_count() << std::endl; // 1}std::cout << wpp.use_count() << std::endl; // 0std::cout << wpc.use_count() << std::endl; // 0return 0; }
3 智能指针的设计与实现
下面是一个简单智能指针的demo。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,构造函数减少引用计数(如果引用计数减至0,则删除基础对象)。智能指针就是模拟指针动作的类。所有的智能指针都会重载 -> 和 * 操作符。智能指针还有许多其他功能,比较有用的是自动销毁。这主要是利用栈对象的有限作用域以及临时对象(有限作用域实现)析构函数释放内存。
#include <iostream>
#include <memory>template<typename T>
class SmartPointer {private:T* _ptr;size_t* _count;
public:SmartPointer(T* ptr = nullptr) :_ptr(ptr) {if (_ptr) {_count = new size_t(1);} else {_count = new size_t(0);}}SmartPointer(const SmartPointer& ptr) {if (this != &ptr) {this->_ptr = ptr._ptr;this->_count = ptr._count;(*this->_count)++;}}SmartPointer& operator=(const SmartPointer& ptr) {if (this->_ptr == ptr._ptr) {return *this;}if (this->_ptr) {(*this->_count)--;if (this->_count == 0) {delete this->_ptr;delete this->_count;}}this->_ptr = ptr._ptr;this->_count = ptr._count;(*this->_count)++;return *this;}T& operator*() {assert(this->_ptr == nullptr);return *(this->_ptr);}T* operator->() {assert(this->_ptr == nullptr);return this->_ptr;}~SmartPointer() {(*this->_count)--;if (*this->_count == 0) {delete this->_ptr;delete this->_count;}}size_t use_count(){return *this->_count;}
};int main() {{SmartPointer<int> sp(new int(10));SmartPointer<int> sp2(sp);SmartPointer<int> sp3(new int(20));sp2 = sp3;std::cout << sp.use_count() << std::endl;std::cout << sp3.use_count() << std::endl;}//delete operator
}
参考:
- 值语义:http://www.cnblogs.com/Solstice/archive/2011/08/16/2141515.html
- shared_ptr使用:http://www.cnblogs.com/jiayayao/archive/2016/12/03/6128877.html
- unique_ptr使用:http://blog.csdn.net/pi9nc/article/details/12227887
- weak_ptr的使用:http://blog.csdn.net/mmzsyx/article/details/8090849
- weak_ptr解决循环引用的问题:http://blog.csdn.net/shanno/article/details/7363480
- C++面试题(四)——智能指针的原理和实现
C++中智能指针的原理、使用、实现相关推荐
- c++11中智能指针的原理,使用,实现
文章目录 理解智能指针的原理 智能指针的使用 shared_ptr的使用 unique_ptr的使用 weak_ptr的使用 循环引用 指针指针的设计和实现: 理解智能指针的原理 c++程序设计中使用 ...
- 【转】C++面试题(四)——智能指针的原理和实现
C++面试题(四)--智能指针的原理和实现 tanglu2004 http://blog.csdn.net/worldwindjp/ C++面试题(一).(二)和(三)都搞定的话,恭喜你来到这里, ...
- 【Smart_Point】C/C++ 中智能指针
C++11智能指针 目录 C++11智能指针 1.1 C++11智能指针介绍 1.2 为什么要使用智能指针 1.2.1 auto_ptr(C++98的方案,C++11已经抛弃)采用所有权模式. 1.2 ...
- C++中智能指针的设计和使用
智能指针(smart pointer)是存储指向动态分配(堆)对象指针的类,用于生存期控制,能够确保自动正确的销毁动态分配的对象,防止内存泄露.它的一种通用实现技术是使用引用计数(reference ...
- 【Boost】boost库中智能指针——shared_ptr
boost::scoped_ptr虽然简单易用,但它不能共享所有权的特性却大大限制了其使用范围,而boost::shared_ptr可以解决这一局限.顾名思义,boost::shared_ptr是可以 ...
- 【Boost】boost库中智能指针——scoped_ptr
boost::scoped_ptr和std::auto_ptr非常类似,是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放.下列代码演示了该指针的基本应用: #include <str ...
- 【Boost】boost库中智能指针——weak_ptr
循环引用: 引用计数是一种便利的内存管理机制,但它有一个很大的缺点,那就是不能管理循环引用的对象.一个简单的例子如下: #include <string> #include <ios ...
- 【Boost】boost库中智能指针概述
这篇文章主要介绍 boost中的智能指针的使用. 内存管理是一个比较繁琐的问题,C++中有两个实现方案: 垃圾回收机制和智能指针.垃圾回收机制因为性能等原因不被C++的大佬们推崇, 而智能指针被认为是 ...
- C++中智能指针详解
1.问题引入 在C++中,静态内存和栈内存外,还有一部分内存称为堆程序用堆来存储动态分配的对象即那些在程序运行时分配的对象,当动态对象不再使用时,我们的代码必须显式的销毁它们.在C++中一般使用&qu ...
最新文章
- 经典不过时,回顾DeepCompression神经网络压缩
- python图像边缘检测
- 【知识发现】python开源哈夫曼编码库huffman
- python 数据结构包_Python Redistr包_程序模块 - PyPI - Python中文网
- 括号配对问题 -- ACM解决方法
- docker 查询或获取私有仓库(registry)中的镜像
- man 输出的帮助信息输出到文件中
- 信度和效度经典例子_浅析经典目标检测评价指标--mmAP(一)
- [C语言] 单向链表的构建以及翻转算法_图文详解(附双向链表构建代码)
- Bailian2808 校门外的树【基础】
- 移动端页面适配方案(viewport)
- 正则化及正则化项的理解
- 华硕ASUS路由器AC86U无线掉线解决方法
- 现代控制理论公式大赏
- fastposter v2.7.0 发布 电商海报编辑器
- 测试发文章测试发文章
- EMC设计理论通俗非科班学习笔记(完结)
- STM32F10xxx20xxx21xxxL1xxxx Cortex-M3程序设计手册 阅读笔记二(5):Cortex-M3处理器能量管理
- pat甲级1014柳神代码解析自学复盘用
- 个人成长:简单写写《乔布斯传》读后感
热门文章
- IntelliJ IDEA 2019.1 windows找不到文件‘chrome’
- VBA IsNull 应用 - 捕获错误并查找未填充的值
- Java-标识符和关键字
- python 按条件选择行和列数据_小白学数据结构-排序算法Python(冒泡、选择、快速、希尔等等)...
- php 获取域名部分,PHP 获取顶级域名 获取域名的函数 parseHost()
- 计算机组成原理第八章课后答案6,计算机组成原理 第八章 复习
- android+模拟器+ram,Android模拟器RAM修改方法 - 尤其是3.0
- 怎样看Linux字体所在目录,Linux下列出所有字体的目录
- mysql表空间界限_MySQL5.7 import表结构报错超出表空间界限
- linux常见基础服务,常用的linux命令的基本使用(一)