• 一个智能指针模板的实现及应用


         智能指针提供了一种安全的处理对象指针及正确的回收对象指针内存的方法,本文给出了一个智能指针模板类,并给出了一个简单的实例

    1. ////////////////////////////SmartPoint.h///////////////////////////////////
    2. #ifndef SMARTPOINT_H_
    3. #define SMARTPOINT_H_
    4. template <class T>
    5. class mem_ptr
    6. {
    7.     T* m_p;
    8.     mem_ptr(T&);
    9. public:
    10.     mem_ptr() : m_p(0) {}
    11.     mem_ptr(T* p) : m_p(p) {}
    12.     ~mem_ptr() { delete m_p; }
    13.     inline T&   operator*()  const { return *m_p; }
    14.     inline T*   operator->() const { return m_p; }
    15.     inline      operator T*()const { return m_p; }
    16.     inline const mem_ptr<T>& operator=(T* p) { set(p); return *this; }
    17.     inline T*   set(T* p)          { delete m_p; m_p = p; return m_p; }
    18.     inline T*   get()        const { return m_p; }
    19.     inline void release()          { m_p = 0; }
    20.     inline bool empty()      const { return m_p == 0; }
    21. };
    22. #endif
    23. ///////////////////////TestSmart.h///////////////////////////////////////
    24. #include <iostream>
    25. using namespace std;
    26. class A
    27. {
    28. public:
    29.     A(int a, int b) : m_a(a), m_b(b)
    30.     {
    31.     }
    32.     void Show()
    33.     {
    34.         cout<<m_a<<endl;
    35.         cout<<m_b<<endl;
    36.     }
    37. private:
    38.     int m_a;
    39.     int m_b;
    40. };
    41. ///////////////////////////main.cpp///////////////////////////////////////
    42. #include "SmartPoint.h"
    43. #include "TestSmart.h"
    44. void main()
    45. {
    46.     mem_ptr<A> m_A = new A(1, 2);
    47.     m_A->Show();
    48.     // 程序退出时调用m_A的析构函数释放对象A的内存
    49. }
  • 相关阅读:
    Fibonacci Again
    N的10000的阶乘
    HDU2141(二分搜索)
    POJ2366(HASH法)
    10106 Product
    UVA 401 Palindromes
    UVA424 Integer Inquiry
    POJ2503(二分搜索)
    mysql重置root密码
    tidb安装haproxy负载均衡
  • 原文地址:https://www.cnblogs.com/zhangyunlin/p/6167970.html
Copyright © 2020-2023  润新知