C++智能指针(二)模拟实现三种智能指针

https://blog.csdn.net/nou_camp/article/details/70186721

在上一篇博客中提到了Auto_ptr(C++智能指针(一)),下面进行模拟实现Auto_ptr 
采用类模板实现

#include<iostream>
using namespace std;
template<class T>
class Autoptr
{
public:Autoptr(T* ptr = NULL):_ptr(ptr){}//Autoptr():_ptr(NULL)//{}Autoptr(Autoptr<T>& ap){this->_ptr = ap._ptr;ap._ptr = NULL;}Autoptr<T>& operator=(Autoptr<T>& sp){if (this != &sp){delete this->_ptr;_ptr = sp._ptr;sp._ptr = NULL;}return *this;}T* operator->(){return _ptr;}T operator*(){return *_ptr;}~Autoptr(){delete _ptr;_ptr = NULL;}void  Reset(T* ptr = 0){if (_ptr != ptr){delete  _ptr;}_ptr = ptr;}
protected:T* _ptr;
};void test()
{//int *p1 = new int(10);//Autoptr<int>ap1(p1);Autoptr<int> ap1(new int(10));//上面的两行代码可以直接用本行代码代替cout << *ap1 << endl;Autoptr<int> ap2(ap1);cout << *ap2 << endl;Autoptr<int> ap3(new int(20));ap3 = ap2;cout << *ap3 << endl;//cout << *ap1 << endl;//会使代码出错
}
int main()
{test();system("pause");return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

这里写图片描述 
这里写图片描述


//cout << *ap1 << endl;//会使代码出错 
这是test函数中的代码,执行这句代码,会使程序崩溃,这是因为ap1已经把它指向的空间交给了ap2去管理,所以ap1已经不具备访问原来自己所指向的空间的权限。所以对它进行解引用是非法的。 
所以可以看清auto_ptr的本质是管理权的转移,即ap1将自己所指向的空间交给ap2来管理,析构也是由ap2来完成。


由上面可知auto_ptr有严重缺陷,所以后来有人写了scopedptr,慢慢发展形成了第三方库。 
scopedptr ->防拷贝,意思就是不能进行拷贝,简单地说是一种简单粗暴的方式。下面模拟实现scopedptr。采用模板类实现。

template<class T>
class scopedptr
{
public:scopedptr(T *ptr):_ptr(ptr){}T* operator->(){return _ptr;}T operator*(){return *_ptr;}~scopedptr(){delete _ptr;_ptr = NULL;}
protected:scopedptr<T>& operator=(const scopedptr<T>& s);scopedptr(scopedptr<T>& ap);
private:T* _ptr;
};
void test()
{scopedptr<int> s1(new int(10));//scopedptr<int> s2(s1);//有错误,编译不通过cout << *s1 << endl;
}
int main()
{test();system("pause");return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

scopedptr中对拷贝构造函数和赋值运算符的重载函数只是进行了声明,并没有去定义这两个函数,而且声明为protected或者是private,这是防止别人在类外对这两个函数进行定义。防止拷贝,所以说scopedptr是一种简单粗暴的方式。


编写程序往往要用到拷贝,这样scopedptr就不能起到相应的作用,所以便有了shared_ptr。 
shared_ptr->采用了引用计数,优点是功能强大,但是也有缺点,缺点是过于复杂,而且会引起循环引用。 
下面模拟实现shared_ptr

#include<iostream>
using namespace std;
template<class T>
class sharedptr
{
public:sharedptr(T* ptr) //构造:_ptr(ptr), _refcount(new int(1)){}sharedptr() //构造:_ptr(NULL), _refcount(new int(1)){}sharedptr(const sharedptr<T>& sp) //拷贝构造:_ptr(sp._ptr), _refcount(sp._refcount){(*_refcount)++;}sharedptr<T>& operator=(const sharedptr<T>& sp) //赋值运算符的重载{if (_ptr != sp._ptr){delete _ptr;delete _refcount;_ptr = sp._ptr;_refcount = sp._refcount;++(*_refcount);}return *this;}~sharedptr() //析构{Realease();}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}T Getrefcount(){return *(_refcount);}inline void Realease(){if (--*_refcount == 0){delete _refcount;delete _ptr;}}void  Reset(T* ptr ,T* refcount){if (_ptr != ptr){delete  _ptr;delete _refcount;}_ptr = ptr;_refcount = refcount;}
public:T* _ptr;T* _refcount;//T _refcount;//有缺陷//int static _refcount;//有缺陷
};
void test()
{sharedptr<int> s1(new int(10));//cout << *s1._refcount << endl;cout << s1.Getrefcount() << endl;sharedptr<int> s2(s1);//cout << *s2._refcount << endl;cout << s2.Getrefcount() << endl;sharedptr<int> s3(new int(20));s3 = s1;//cout << *s3._refcount << endl;cout << s3.Getrefcount() << endl;
}
int main()
{test();//*sharedptr<int> sp;  // 验证Reset//sp.Reset(new int,new int(1));       //*sp = 10;//cout << *sp << endl;//sp.Reset(new int, new int(1));  //*sp = 20;//cout << *sp << endl;//sp.Reset(); system("pause");return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

这里写图片描述


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/383752.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Prime Distance On Tree-树分治+FFT

题目描述 Problem description. You are given a tree. If we select 2 distinct nodes uniformly at random, what’s the probability that the distance between these 2 nodes is a prime number? Input The first line contains a number N: the number of nodes in this…

C++智能指针(三)总结

https://blog.csdn.net/nou_camp/article/details/70195795 在上一篇博客中&#xff08;C智能指针&#xff08;二&#xff09;&#xff09;模拟实现了三种智能指针。 其中最好的就是shared_ptr,但是这并不代表它就是最完美的&#xff0c;它也有问题&#xff0c;这个问题就是循环…

POJ2114-Boatherds-树分治

题目描述 Boatherds Inc. is a sailing company operating in the country of Trabantustan and offering boat trips on Trabantian rivers. All the rivers originate somewhere in the mountains and on their way down to the lowlands they gradually join and finally th…

c++11 你需要知道这些就够了

https://blog.csdn.net/tangliguantou/article/details/50549751c11新特性举着火把寻找电灯今天我就权当抛砖引玉&#xff0c;如有不解大家一起探讨。有部分内容是引用自互联网上的内容&#xff0c;如有问题请联系我。T&& 右值引用 std::move 右值引用出现之前我们只能…

HDU5977-Garden of Eden-树分治+FWT

题目描述 When God made the first man, he put him on a beautiful garden, the Garden of Eden. Here Adam lived with all animals. God gave Adam eternal life. But Adam was lonely in the garden, so God made Eve. When Adam was asleep one night, God took a rib fro…

C++11新特性学习

https://blog.csdn.net/tennysonsky/article/details/778170481、什么是C11C11标准为C编程语言的第三个官方标准&#xff0c;正式名叫ISO/IEC 14882:2011 - Information technology -- Programming languages -- C。在正式标准发布前&#xff0c;原名C0x。它将取代C标准第二版I…

C++ override 关键字用法

override关键字作用&#xff1a; 如果派生类在虚函数声明时使用了override描述符&#xff0c;那么该函数必须重载其基类中的同名函数&#xff0c;否则代码将无法通过编译。举例子说明struct Base {virtual void Turing() 0;virtual void Dijkstra() 0;virtual void VNeumann…

Gym - 101981I-MagicPotion-最大流

题目描述 There are n heroes and m monsters living in an island. The monsters became very vicious these days, so the heroes decided to diminish the monsters in the island. However, the i-th hero can only kill one monster belonging to the set Mi. Joe, the st…

c++仿函数 functor

https://www.cnblogs.com/decade-dnbc66/p/5347088.html内容整理自国外C教材先考虑一个简单的例子&#xff1a;假设有一个vector<string>&#xff0c;你的任务是统计长度小于5的string的个数&#xff0c;如果使用count_if函数的话&#xff0c;你的代码可能长成这样&#…

HDU4812-D Tree-树分治

题目描述 There is a skyscraping tree standing on the playground of Nanjing University of Science and Technology. On each branch of the tree is an integer (The tree can be treated as a connected graph with N vertices, while each branch can be treated as a v…

成为C++高手之实战项目

https://blog.csdn.net/niu_gao/article/details/51458721 在内存中模拟出一副牌&#xff0c;然后模拟洗牌&#xff0c;发牌等动作。 流程是这样的&#xff1a;构建一副牌保存到一个数组中—洗牌—创建玩家—向玩家发牌–输出每个玩家的牌。 #include <stdio.h> #include…

C++中String类的实现

https://www.cnblogs.com/zhizhan/p/4876093.html原文&#xff1a;http://noalgo.info/382.html String是C中的重要类型&#xff0c;程序员在C面试中经常会遇到关于String的细节问题&#xff0c;甚至要求当场实现这个类。只是由于时间关系&#xff0c;可能只要求实现构造函数、…

Ubuntu软件更新失败

刚安装好Ubuntu以后需要将系统的软件都更新一下&#xff0c;但是遇到一个问题就是下载仓库信息失败&#xff0c;大概是这个样子的错误&#xff1a; 经国遇到这样的问题可以试一下下面这个命令&#xff1a; sudo rm -rf /var/lib/apt/lists/* sudo apt-get update参考网址&…

getsockname函数与getpeername函数的使用

https://www.tuicool.com/articles/V3Aveygetsockname和getpeername函数 getsockname函数用于获取与某个套接字关联的本地协议地址 getpeername函数用于获取与某个套接字关联的外地协议地址 定义如下&#xff1a;[cpp] view plaincopy#include<sys/socket.h> int gets…

Ubuntu根目录空间不足

自己在固态硬盘上安装的Ubuntu&#xff0c;结果只用了一天就显示磁盘空间不足。查看空间以后发现Ubuntu自己安装的时候默认给根目录分配的是10GB,然而我们下载的软件以及环境等一般都安装在根目录空间下&#xff0c;尤其是/usr目录所占的空间很大。 不得已我在网上查找了如何给…

Linux命令【一】基本命令

shell命令和bash命令相同&#xff0c;指的是命令解析器 快捷键 history 所有的历史命令ctrl P 向上滚动命令 ctrl N 向下滚动命令 ctrlB将光标向前移动 ctrlF将光标向后移动 ctrlA移动到命令行头部 ctrlE移动到命令行尾部 光标删除操作&#xff1a;删除光标前面字符ctrlh或…

The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement

http://www.jb51.net/article/119654.htmThe MySQL server is running with the --skip-grant-tables option so it cannot execute this statement 意思貌似MYSQL还运行在 --skip-grant-tables模式&#xff0c;如何让他回到原来的模式 第一种方法&#xff1a;原来在mysql.ini文…

解决Ubuntu“下载额外数据文件失败 ttf-mscorefonts-installer”的问题

参考博客&#xff1a;传送门 下载[ttf-mscorefonts-installer.zip](https://pan.baidu.com/s/1i5rLfMH) 密码: h76g 然后解压到下载的目录&#xff0c;在当前目录执行命令&#xff1a; sudo dpkg-reconfigure ttf-mscorefonts-installer这条命令手动指定文件夹的位置,重新配置…

【C语言】单链表的相关热点面试题(包括:从尾到头打印,逆置,冒泡,寻找中间节点,倒数k节点)

https://blog.csdn.net/hanjing_1995/article/details/51539599从尾到头打印单链表[cpp] view plaincopyvoid FromTailToHeadPrint(SListNode*& head) { stack<SListNode*> s; SListNode* cur head; while (cur) { s.push(cur); …

Linux命令【二】终端+Vim

需要先安装net-tools ifconfig eth0 网卡&#xff0c;硬件地址为MAC 地址&#xff0c;网卡编号&#xff0c;绝对不会重复 lo 回环地址 测试两台主机之间能否通信&#xff1a;ping IP或域名 [-c 4//回馈四条信息 -i//每隔多少秒回馈一次] 得到域名对应的IPnslookup 域名得到域…