C++ 实现智能指针(带引用计数)

叁歲伎倆 2022-12-31 02:23 126阅读 0赞
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. //实现一个带引用计数的智能指针
  4. /* 思路:对象有两个成员变量,一个成员变量指向资源,一个成员变量指向计数。(计数必须在堆上分配) 构造函数:让资源指针指向资源,并且创建一个和这个资源配对的int=1。 析构函数:判断int==0,决定是否释放资源 拷贝构造:int++,_p指向同一个资源 拷贝赋值运算符:检查自赋值,释放之前资源,赋值 解引用*:返回引用T 箭头:返回p指针、 */
  5. template<typename T>
  6. class Cnt{
  7. public:
  8. Cnt(T*p=NULL):_p(p){
  9. if(_p!=NULL){
  10. count=1;
  11. }else{
  12. count=0;
  13. }
  14. }
  15. int getcnt(){
  16. return count;
  17. }
  18. void sub(){
  19. count--;
  20. }
  21. void add(){
  22. count++;
  23. }
  24. private :
  25. T *_p;
  26. int count;
  27. };
  28. template<typename T>
  29. class ssmart{
  30. public:
  31. ssmart(T*p=NULL):_p(p),cnt(){ //nullptr
  32. cnt= new Cnt<T>(_p);
  33. }
  34. ~ssmart(){
  35. if(cnt->getcnt()==1){
  36. delete cnt;
  37. delete _p;
  38. }else{
  39. cnt->sub();
  40. }
  41. }
  42. ssmart(const ssmart&smart){
  43. _p=smart._p;
  44. cnt=smart.cnt;
  45. cnt->add();
  46. }
  47. ssmart& operator=(const ssmart&smart){
  48. if(this==smart)return *this;
  49. if(_p!=NULL){
  50. cnt->sub();
  51. if(!cnt->getcnt()){
  52. delete cnt;
  53. delete _p;
  54. }
  55. }
  56. _p=smart._p;
  57. cnt->add();
  58. return *this;
  59. }
  60. T& operator*(){
  61. return *_p;
  62. }
  63. T& operator->(){
  64. return _p;
  65. }
  66. private:
  67. T*_p;
  68. Cnt<T>* cnt;
  69. };
  70. int main(){
  71. ssmart<int> p(new int);
  72. *p=15;
  73. cout<<*p<<endl;
  74. ssmart<int> p1(p);
  75. cout<<*p1<<endl;
  76. return 0;
  77. }
  78. ########################################################################################
  79. 1.29练习:
  80. #include<bits/stdc++.h>
  81. using namespace std;
  82. template<typename T>
  83. class smart{
  84. public :
  85. smart(T *p){
  86. _p=p;
  87. _cnt= new int(1);
  88. cout<<"ok"<<endl;
  89. }
  90. ~smart(){
  91. (*_cnt)--;
  92. if(*_cnt==0)delete _p;
  93. }
  94. smart(const smart&rhs){
  95. _cnt=rhs._cnt;
  96. (*_cnt)++;
  97. _p=rhs._p;
  98. }
  99. smart& operator=(const smart&rhs){
  100. if(&rhs==this)return *this;
  101. if(*_cnt-- == 1){
  102. delete _p;
  103. }
  104. _cnt=rhs._cnt;
  105. (*_cnt)++;
  106. _p=rhs._p;
  107. return *this;
  108. }
  109. int& operator*(){
  110. return *_p;
  111. }
  112. int* operator->(){
  113. return _p;
  114. }
  115. void show(){
  116. cout<<"cnt:"<< *_cnt<<" "<<"p:"<< *_p <<endl;
  117. }
  118. private :
  119. int *_cnt;
  120. T *_p;
  121. };
  122. int main(){
  123. int *p=new int(1100) ;
  124. smart<int> data(p);
  125. *data=100;
  126. cout<<*data<<endl;
  127. data.show();
  128. return 0;
  129. }

发表评论

表情:
评论列表 (有 0 条评论,126人围观)

还没有评论,来说两句吧...

相关阅读

    相关 shared_ptr基于引用计数智能指针实现

    智能指针是什么 简单来说,智能指针是一个类,它对普通指针进行封装,使智能指针类对象具有普通指针类型一样的操作。具体而言,复制对象时,副本和原对象都指向同一存储区域,如果通