广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++ 智能指针代码解析
  • 865
分享到

C++ 智能指针代码解析

2024-04-02 19:04:59 865人浏览 独家记忆
摘要

目录前言1,aoto_ptr2,unique_ptr3,share_ptr4, weak_ptr总结前言 如果在程序中使用new从堆分配内存,等到不再需要时,应使用delete将其释

前言

如果在程序中使用new从堆分配内存,等到不再需要时,应使用delete将其释放,c++引入了智能指针auto_ptr,以帮助自动完成这个过程,但是aoto_ptr也有其局限性,因此从Boost库中又引入了三种智能指针unique_ptr shared_ptr weak_ptr。

1,aoto_ptr


// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <memory>
#include <string>
#include <iOStream>
#include <ostream>
using namespace std;
int _tmain(int arGC, _TCHAR* argv[])
{
	auto_ptr<string>  ptr1(new string("this is ptr!"));
	auto_ptr<string>  ptr2;
	ptr2 = ptr1;
	cout << &ptr2<<endl;
	cout << *ptr2 << endl;
	return 0;
}
  • output :

003AFBC0
this is ptr!

但是如果输出的是ptr1,程序会如何呢?


#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	auto_ptr<string>  ptr1(new string("this is ptr!"));
	auto_ptr<string>  ptr2;
	ptr2 = ptr1;
	cout << &ptr1 <<endl;
	cout << *ptr1 << endl;  #这一步程序会崩溃
	return 0;
}

崩溃原因: 首先ptr2 = ptr1表示ptr1将访问的权限给了ptr2,同时意味了ptr1已经没有访问字符串的权限,因此会报错。

那如何解决这个问题呢?引入了unique_ptr

2,unique_ptr


#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	unique_ptr<string> ptr1(new string("this is unique_ptr"));
	unique_ptr<string> ptr2;
	ptr2 = ptr1;  #这一步编译器会报错
	return 0;
}

unique_ptr 替代auto_ptr实现独占式,可以理解成,同一时刻只能有一个unique_ptr指向给定对象,unique_ptr对象始终是关联的原始指针的唯一所有者。无法复制unique_ptr对象,它只能移动。(这样可以保证,不会出现auto_ptr那样运行时会出现的隐藏内存崩溃问题)


int _tmain(int argc, _TCHAR* argv[])
{
	unique_ptr<string> ptr1(new string("this is unique_ptr"));
	unique_ptr<string> ptr2;
	cout << &ptr1 << endl;
	unique_ptr<string> ptr3(new string("other unique_ptr"));
	cout << &ptr3 << endl;
	cout << *ptr3 << endl;
	return 0;
}
  • output:

00D9F8B4
00D9F89C
other unique_ptr

3,share_ptr


// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
class base{
public:
	base()
	{
		cout << "begin..." << endl;
	};
	~base()
	{
		cout << "end..." << endl;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	base *a = new base();
	shared_ptr<base> ptr1(a);
	//shared_ptr<base> ptr2(a);    ## 如果加上这句程序会崩溃,双重管理陷阱,a对象被删除了两次
	return 0;
}
  • output:

begin...

end...

  • share_ptr的循环陷阱

#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
class CB;
class CA
{
public:
	CA()
	{
		cout << "CA call ..."<< endl;
	}
	~CA()
	{
		cout << "~CA call..."<< endl;
	}
	void setPtr(shared_ptr<CB> &ptr)
	{ 
		m_ptr_b = ptr;
	}
	int getCount()
	{
		return m_ptr_b.use_count();
	}
private:
	shared_ptr<CB> m_ptr_b;
};
class CB
{
public:
	CB()
	{
		cout << "CB call..." << endl;
	}
	~CB()
	{
		cout << "~CB call..." << endl;
	}
	void setPtr(shared_ptr<CA> ptr)
	{
		m_ptr_a = ptr;
	}
	int getCount()
	{
		return m_ptr_a.use_count();
	}

private:
	shared_ptr<CA> m_ptr_a;
};
int _tmain(int argc, _TCHAR* argv[])
{
	shared_ptr<CA> ptr_a(new CA);
	shared_ptr<CB> ptr_b(new CB);
	cout << " CA count is : " << ptr_a->getCount()<<endl;
	cout << "CB count is:" << ptr_b->getCount()<< endl;
	ptr_a->setPtr(ptr_b);
	ptr_b->setPtr(ptr_a);
	cout << " CA count is : " << ptr_a->getCount() << endl;
	cout << "CB count is:" << ptr_b->getCount() << endl;
	return 0;
}

上面这段程序的思路用下面张图可以清晰的表示

图片和代码主要参考的是这篇很棒的博文:智能指针(三):weak_ptr浅析

在这里插入图片描述

在这里插入图片描述

运行结果后发现并没有调用析构函数释放内存,以后存在内存泄漏的风险

那如何去解决这个问题呢?,可以通过引入weak_ptr来解决,但是weak_ptr需要与share_ptr配合使用

4, weak_ptr

通过在两个类中的一个成员变量改为weak_ptr对象,因为weak_ptr不会增加引用计数,使得引用形不成环,最后就可以正常的释放内部的对象,不会造成内存泄漏


class CB
{
public:
	CB()
	{
		cout << "CB call..." << endl;
	}
	~CB()
	{
		cout << "~CB call..." << endl;
	}
	void setPtr(shared_ptr<CA> ptr)
	{
		m_ptr_a = ptr;
	}
	int getCount()
	{
		return m_ptr_a.use_count();
	}

private:
	///shared_ptr<CA> m_ptr_a;
	weak_ptr<CA> m_ptr_a;  ## 改为weak_ptr对象
};

在这里插入图片描述

在这里插入图片描述

总结

遇到这类新的概念或者方法时,一定要不嫌麻烦的一行一行代码的去敲,在敲的过程中去理解吸收,如果只看不实践,很有可能理解不深刻,无法体会到其中的原理和机制,所以对待问题一定要沉下心来多实践。

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!

--结束END--

本文标题: C++ 智能指针代码解析

本文链接: https://www.lsjlt.com/news/154708.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++ 智能指针代码解析
    目录前言1,aoto_ptr2,unique_ptr3,share_ptr4, weak_ptr总结前言 如果在程序中使用new从堆分配内存,等到不再需要时,应使用delete将其释...
    99+
    2022-11-12
  • C++智能指针实例代码分析
    这篇文章主要讲解了“C++智能指针实例代码分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++智能指针实例代码分析”吧!一、内存泄漏-永恒的话题动态申请堆空间,用完后不归还C++ 语言中...
    99+
    2023-06-30
  • C++11中的智能指针shared_ptr、weak_ptr源码解析
    目录1、前言2、源码准备3、智能指针概念4、源码解析4.1、shared_ptr解析4.1.1、shared_ptr4.1.2、__shared_ptr4.1.3、__shared_...
    99+
    2022-11-12
  • C++深入分析讲解智能指针
    目录1.简介2.unique_ptr指针(独占指针)3.shared_ptr指针(共享所有权)4.weak_ptr(辅助作用)5.自实现初级版智能指针6.总结1.简介 程序运行时存在...
    99+
    2022-11-13
  • C++SmartPointer智能指针详解
    目录一、为啥使用智能指针呢二、shared_ptr智能指针三、unique_ptr智能指针四、weak_ptr智能指针五、智能指针怎么解决交叉引用,造成的内存泄漏5.1 交叉引用的栗...
    99+
    2022-11-13
  • 【C++】智能指针(RAII)详解
        我们在上篇文章中(异常处理详解)提到了 RAII 。那么本篇文章会对此进行详解。重点是智能指针的详解。其中会讲解到 RAII 思想、auto_ptr、unique_ptr、shared_ptr、weak_ptr、循环引用问题。希...
    99+
    2023-09-06
    c++ 开发语言
  • C++智能指针shared_ptr
    目录1、什么是shared_ptr?2、shared_ptr支持哪些操作?3、如何创建shared_ptr的实例?4、什么是shared_ptr的引用计数?如何查看?5、shared...
    99+
    2022-11-13
  • C++智能指针之shared_ptr详解
    目录共享指针的初始化方式常用成员函数shared_ptr内存模型make_shared的优缺点优点缺点引用计数比较运算符总结共享指针的初始化方式 1.裸指针直接初始化,但不能通过隐式...
    99+
    2022-11-13
  • C语言智能指针之weak_ptr浅析
    目录前言使用环境测试过程现象分析总结前言 weak_ptr这个指针天生一副“小弟”的模样,也是在C++11的时候引入的标准库,它的出现完全是为了弥补它老大shared_ptr天生有缺...
    99+
    2022-11-12
  • C++智能指针使用实例分析
    这篇文章主要介绍了C++智能指针使用实例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C++智能指针使用实例分析文章都会有所收获,下面我们一起来看看吧。1.简介程序运行时存在静态空间、栈和堆区,用堆来存储动...
    99+
    2023-06-30
  • C++超详细讲解智能指针
    目录一、内存泄漏-永恒的话题二、深度思考三、智能指针分析四、小结一、内存泄漏-永恒的话题 动态申请堆空间,用完后不归还C++ 语言中没有垃圾回收的机制指针无法控制所指堆空间的生命周期...
    99+
    2022-11-13
  • C/C++中智能指针的用法详解
    目录前言一、什么是智能指针二、使用方法1.shared_ptr2.unique_ptr3.weak_ptr前言 本章主要介绍一些C/C++中智能指针的实现原理以及如何使用 一、什么是...
    99+
    2023-01-04
    C++智能指针使用 C++智能指针
  • C++的智能指针使用实例分析
    今天小编给大家分享一下C++的智能指针使用实例分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。什么是RAIIRAII(Re...
    99+
    2023-06-29
  • C++特性之智能指针shared_ptr详解
    目录1.创建指针对象2.分离关联的原始指针3.与普通指针比较4.NULL检测shared_ptr 是C++11提供的一种智能指针类,它足够智能,可以在任何地方都不使用时自动删除相关指...
    99+
    2022-12-08
    C++智能指针shared_ptr C++智能指针 C++ shared_ptr
  • c++智能指针的超详细讲解
    目录1.什么是智能指针2.原始指针的问题3.unique_ptr4.shared_ptr5.shared_ptr使用需要注意的点5.1 不能将一个原始指针初始化多个shared_pt...
    99+
    2022-11-13
  • C++智能指针shared_ptr与weak_ptr的实现分析
    目录shared_ptrweak_ptr内存模型RefCnt 和 Mdel实现shared_ptr 实现weak_ptr 实现shared_from_this()循环引用shared...
    99+
    2022-11-13
  • C++中Boost的智能指针scoped_ptr
    boost::scoped_ptr和std::auto_ptr非常类似,是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放。下列代码演示了该指针的基本应用: #includ...
    99+
    2022-11-13
  • c++智能指针unique_ptr的使用
    目录1.为什么需要unique_ptr2.什么是unique_ptr3.unique_ptr特性4.如何使用unique_ptr4.1简单使用4.2指向数组5.unique_ptr需...
    99+
    2022-11-12
  • C++中Boost的智能指针shared_ptr
    boost::scoped_ptr虽然简单易用,但它不能共享所有权的特性却大大限制了其使用范围,而boost::shared_ptr可以解决这一局限。顾名思义,boost::shar...
    99+
    2022-11-13
  • C++中Boost的智能指针weak_ptr
    循环引用: 引用计数是一种便利的内存管理机制,但它有一个很大的缺点,那就是不能管理循环引用的对象。一个简单的例子如下: #include <string> #includ...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作