智能指针类模板——创建智能指针类模板

人盡茶涼 提交于 2019-12-08 21:47:27
#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中都提供了对智能指针的支持

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!