当前位置: 首页 > news >正文

c++介绍智能指针 十二(2)

智能指针share_ptr,与unique_ptr不同,多个shar_ptr对象可以共同管理一个指针,它们通过一个共同的引用计数器来管理指针。当一个智能指针对象销毁时,计数器减一。当计数器为0时,会将所指向的内存对象释放。

#include<memory>
#include<iostream>
#include<vector>
#include<algorithm>
#include<chrono>
using namespace std;

class Rectangle {

public:
	Rectangle(double w, double h) :width(w), height(h) {}
	~Rectangle() {}
	double area()
	{
		return width * height;
	}
private:
	double width;
	double height;
};
int main()
{
	using std::shared_ptr;
	shared_ptr<Rectangle>p1(new Rectangle(1, 5));
	shared_ptr<Rectangle>p2 = p1;
	shared_ptr<Rectangle>p3(p2);
	cout << p1.use_count() << endl;
}

打印结果 

 另外share_ptr提供几个辅助函数,用于对封装指针类型得静态转换,动态转换以及常量转换,它们分别是dynamic_pointer_cast,static_pointer_cast和const_point_cast.

#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class Base {
public:
	virtual ~Base() {}

};
class Derive :public Base {};

int main()
{
	shared_ptr<Base>sp1(new Derive());
	shared_ptr<Derive>sp2 = dynamic_pointer_cast<Derive>(sp1);
	shared_ptr<Base>sp3 = static_pointer_cast<Base>(sp2);
	cout << "use count:" << sp1.use_count() << endl;

虽然他们封装得对象类型不同,但他们都是指向同一个对象,所以引用计数为3.

在使用share_ptr时容易出现一个问题,就是当出现循环引用时,无法释放所指向的资源。造成内存泄漏。

#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class Person
{
public:
	Person(string name) :m_name(name) {	
		cout << m_name << "constructed" << endl;
	}
	~Person()
	{
		cout << m_name << "desconstructed" << endl;
	}
	void setParter(const shared_ptr<Person>& other)
	{
		m_partner = other;
	}
private:
	string m_name;
	shared_ptr<Person>m_partner;
};

int main()
{
	vector<shared_ptr<Person>>people;
	people.push_back(shared_ptr<Person>(new Person("张三")));
	people.push_back(shared_ptr<Person>(new Person("李四")));
	people.push_back(shared_ptr<Person>(new Person("王五")));
	people[0]->setParter(people[1]);
	people[1]->setParter(people[2]);
	people[2]->setParter(people[0]);
	return 0;
}

打印结果

这里people存放了三个person对象,由于person 的成员变量m_partner也是指向Person对象的共享智能指针,接下来这三条语句,peoeple中的第一个元素的m_partner指向了第二个元素中的Person对象,第二个元素的m_partner指向了第三个元素中Person的对象,第三个元素的m_partner指向了第一个元素中的Person对象。这样每个对象的引用计数都是2.当people向量离开作用域销毁后,会将每个对象的引用计数减1,但每个对象的成员m_partner仍存在,所以无法删除Person对象,最终导致内存的泄露。为了防止这种情况出现,就避免出现share_ptr循环引用情况。或者结合使用另外一种智能指针weak_ptr;例如将Person成员变量中的share_ptr改为weak_ptr,当peolple离开作用域销毁后,他所指向的对象也都自动销毁。

weak_ptr不能单独使用,需要结合share_ptr一起使用。我weak_ptr的对象可以将share_ptr作为构造函数的参数初始化,或者定义一个空的weak_ptr,然后将share_ptr对象赋值给它。如下代码

#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class A {};
int main()
{
	shared_ptr<A> sp1 = make_shared<A>();
	weak_ptr<A>wp1(sp1);
	weak_ptr<A>wp2;
	wp2 =sp1;
	cout << "use count: " << wp2.use_count() << endl;

}

打印结果

weak_ptr的主要特征是,只对share_ptr所管理的的对象进行观测,不会改变对象的引用计数。如下代码

#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class Rectangle {

public:
	Rectangle(double w, double h) :width(w), height(h) {}
	~Rectangle() {}
	double area()
	{
		return width * height;
	}
private:
	double width;
	double height;
};
int main()
{
	weak_ptr<Rectangle>w_sp1;
	{
		shared_ptr<Rectangle>sp1(new Rectangle(1, 2));
		shared_ptr<Rectangle>sp2 = sp1;
		w_sp1 = sp2;
		cout << "作用域内部usecount=" << w_sp1.use_count() << endl;
	}
	cout << "作用域外部usercount=" << w_sp1.use_count() << endl;
	cout << "expired=" << w_sp1.expired() << endl;//为1时所观测的对象不可用
}

打印结果

我们可以通过weak_ptr使用lock函数来获得一个shared_ptr以获得封装对象的控制权。在下面这个例子里我们输出share_ptr里封装对象指针,由于share_ptr重载了插入运算符,所以可以直接打印出封装的指针的值。

#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class Rectangle {

public:
	Rectangle(double w, double h) :width(w), height(h) {}
	~Rectangle() {}
	double area()
	{
		return width * height;
	}
private:
	double width;
	double height;
};
int main()
{
	weak_ptr<Rectangle>w_sp1;
	{
		shared_ptr<Rectangle>sp1(new Rectangle(1, 2));
		shared_ptr<Rectangle>sp2 = sp1;
		w_sp1 = sp2;
		shared_ptr<Rectangle>sp3 = w_sp1.lock();
		cout << "作用域内部sp3=" << sp3 << endl;
	}
	shared_ptr<Rectangle>sp3 = w_sp1.lock();
	cout << "作用域外部sp3=" << sp3 << endl;
	cout << "expired=" << w_sp1.expired() << endl;//为1时所观测的对象不可用
}

打印结果

可以看到在作用域里面share_ptr是个有效指针,而在作用域外是个空指针。所以当我们使用weak_ptr观察对象是否为空指针时,并不需要使用use_count或expired来判断 ,而是可以直接调用lock函数获得一个share_ptr对象,如果share_ptr包含的指针非空那么就可用。由于lock对象是个原子操作,是一个不可分割的操作,当原子操作执行进程中时,其它线程不能读取,修改或者中断操作的数据,因此,使用lock函数保证了多线程时获得的share_ptr中的对象是安全有效的,此外,在多线程环境下,当使用expired函数时,只有当expired返回true时才是有意义的。

下面时weak_ptr和share_ptr直接的关系。

http://www.dtcms.com/a/66830.html

相关文章:

  • 【C++】 —— 笔试刷题day_4
  • 【Mac 系统卸载 Go 语言完整指南】
  • 【微知】plantuml在泳道图中如何将多个泳道框起来分组并且设置颜色?(box “浏览器“ #LightGreen endbox)
  • 重生之我在学Vue--第11天 Vue 3 高级特性
  • Mybatis语法bug
  • 吴恩达机器学习笔记复盘(三)Jupyter NoteBook
  • Adobe Acrobat Pro setting
  • 第3关:完美综合运算式
  • 如何修改 Ubuntu 软件源(镜像源)
  • Javascript进阶
  • Kotlin中使用DataBinding绑定RecyclerView并数据两列显示
  • 点云大数据在低空经济中的应用:三维激光雷达技术探索
  • 12.16some pro about py model
  • QT中的布局管理
  • 火绒终端安全管理系统V2.0--分层防御之内容过滤层
  • MongoDB 和 Elasticsearch的区别、优缺点对比,以及选型建议
  • PyQt基础——简单的图形化界面(窗口)
  • Mybatis的基本使用
  • 描述符(descriptor)协议如何实现Python的属性访问控制?
  • CV:图像的直方图均衡化
  • pyinstall将python打包成.exe运行时就不需要python环境了
  • 防止手机验证码被刷:React + TypeScript 与 Node.js + Express 的全面防御策略
  • 【Repos系列】Bandersnatch同步原理
  • docker安装及使用介绍
  • 前端构建工具进化论:从Grunt到Turbopack的十年征程
  • 广播机制(Broadcasting)
  • vue3 前端路由权限控制与字典数据缓存实践(附Demo)
  • STM32F407 cubeIDE Bootloader APP 如何写
  • 【从零开始学习计算机科学】数据库系统(二)关系数据库 与 关系代数
  • AI学习——深度学习核心技术深度解析