zoukankan      html  css  js  c++  java
  • C++语法小记---智能指针

    智能指针
    • 用于缓解内存泄露的问题

    • 用于替代原生指针

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

    • 方法

      • 在智能指针的析构函数中调用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 }
  • 相关阅读:
    line-block,white-space,overflow
    JS操作cookie
    C#的位运算
    小常识:变量的修饰符和DEMO
    JS等号的小注释
    关于谷歌浏览器的小常识
    P2568 GCD
    P2522 [HAOI2011]Problem b
    P3455 [POI2007]ZAP-Queries
    P1447 [NOI2010]能量采集
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11295230.html
Copyright © 2011-2022 走看看