加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++语法小记---智能指针

发布时间:2020-12-16 10:47:39 所属栏目:百科 来源:网络整理
导读:智能指针 用于缓解内存泄露的问题 用于替代原生指针 军规:只能指向堆空间中的对象或变量 方法 在智能指针的析构函数中调用delete 重载"-"操作符,只能重载成成员函数,且不能有参数 禁止智能指针的算术运算 一块对空间只能被一个智能指针指向 ? 例子 1 #inc
智能指针
  • 用于缓解内存泄露的问题

  • 用于替代原生指针

  • 军规:只能指向堆空间中的对象或变量

  • 方法

    • 在智能指针的析构函数中调用delete

    • 重载"->"操作符,只能重载成成员函数,且不能有参数

    • 禁止智能指针的算术运算

    • 一块对空间只能被一个智能指针指向

?

例子

 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 class Persion
 7 {
 8     string name;
 9     int age;
10 public:
11     Persion(string name,int age)
12     {
13         this->name = name;
14         this->age = age;
15         cout<<"Persion()"<<endl;
16     }
17     
18     void show()
19     {
20         cout<<"name = "<<name<<endl;
21         cout<<"age = "<<age<<endl;
22     }
23     
24     ~Persion()
25     {
26         cout<<"~Persion()"<<endl;
27     }
28 };
29 
30 template<typename T>
31 class Pointer
32 {
33     T* m_ptr;
34 public:
35     Pointer(T* ptr)
36     {
37         m_ptr = ptr;
38     }
39     
40     Pointer(const Pointer& other)
41     {
42         m_ptr = other.m_ptr;
43         const_cast<Pointer&>(other).m_ptr = NULL;
44     }
45     
46     Pointer& operator = (const Pointer& other)
47     {
48         if(this != &other)
49         {
50             if(m_ptr)
51             {
52                 delete m_ptr;
53             }
54             
55             m_ptr = other.m_ptr;
56             const_cast<Pointer&>(other).m_ptr = NULL;
57         }
58         return *this;
59     }
60     
61     T* operator -> ()
62     {
63         return m_ptr;
64     }
65     
66     ~Pointer()
67     {
68         if(m_ptr)
69         {
70             delete m_ptr;
71         }
72         m_ptr = NULL;
73     }
74 };
75 
76 int main()
77 {
78     Pointer<Persion> p = new Persion("zhangsan",20);
79     Pointer<Persion> p1 = NULL;
80     p1 = p;
81     p1->show();
82     return 0;
83 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读