zoukankan      html  css  js  c++  java
  • 智能指针类模板——创建智能指针类模板

    #ifndef _SMARTPOINTER_H_
    #define _SMARTPOINTER_H_
    
    template
    < typename T >
    class SmartPointer
    {
        T* mp;
    public:
        SmartPointer(T* p = NULL)
        {
            mp = p;
        }
    
        SmartPointer(const SmartPointer<T>& obj)
        {
            mp = obj.mp;
            const_cast<SmartPointer<T>&>(obj).mp = NULL;
        }
    
        SmartPointer<T>& operator = (const SmartPointer<T>& obj)
        {
            if( this != &obj )
            {
                delete mp;
                mp = obj.mp;
                const_cast<SmartPointer<T>&>(obj).mp = NULL;
            }
    
            return *this;
        }
    
        T* operator -> ()
        {
            return mp;
        }
    
        T& operator * ()
        {
            return *mp;
        }
    
        bool isNull()
        {
            return (mp == NULL);
        }
    
        T* get()
        {
            return mp;
        }
    
        ~SmartPointer()
        {
            delete mp;
        }
    };
    
    #endif
    #include <iostream>
    #include <string>
    #include "SmartPointer.h"
    
    using namespace std;
    
    class Test
    {
        string m_name;
    public:
        Test(const char* name)
        {
            cout << "Hello, " << name << "." << endl;
    
            m_name = name;
        }
    
        void print()
        {
            cout << "I'm " << m_name << "." << endl;
        }
    
        ~Test()
        {
            cout << "Goodbye, " << m_name << "." << endl;
        }
    };
    
    int main()
    {
        SmartPointer<Test> pt(new Test("hello world"));
    
        cout << "pt = " << pt.get() << endl;
    
        pt->print();
    
        cout << endl;
    
        SmartPointer<Test> pt1(pt);
    
        cout << "pt = " << pt.get() << endl;
        cout << "pt1 = " << pt1.get() << endl;
    
        pt1->print();
    
        return 0;
    }

    小结:
    智能指针是C++中自动内存管理的主要手段
    智能指针在各种平台上都有不同的表现形式
    智能指针能够尽可能的避开内存相关的问题
    STL和Qt中都提供了对智能指针的支持

  • 相关阅读:
    游标定位:Cursor类
    拨号操作——android.intent.action.CALL
    按键——Button事件监听器
    文本框——EditText
    配置文件:mainfest.xml
    win7如何设置以管理员身份运行
    随机数:rand()
    std::string 和 CString问题
    文件操作:rewind()
    文件操作:fread()和fwrite()
  • 原文地址:https://www.cnblogs.com/-glb/p/12008058.html
Copyright © 2011-2022 走看看