幻想小说网 酷文学 深夜书屋 叮当小说网 找小说网 无限小说网 红尘小说网

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

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

  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. }

posted on 2009-01-08 10:21  张云临  阅读(156)  评论(0编辑  收藏  举报

导航