数据结构 第27课 再论智能指针(上)---------1--------狄泰软件学院

文章引用: 1

文章引用: 2

Pointer.h

#ifndef POINTER_H
#define POINTER_H

#include "Object.h"

namespace DTLib
{
    
    
template < typename T >
class Pointer : public Object
{
    
    
protected:
    T* m_pointer;
public:
    Pointer(T* pointer = NULL)
    {
    
    
        m_pointer = pointer;
    }

    T* operator -> ()
    {
    
    
        return m_pointer;

    }

    T& operator * ()
    {
    
    
        return *m_pointer;

    }

    bool isNull()
    {
    
    
        return( m_pointer == NULL );
    }

    T* get()
    {
    
    
        return m_pointer;

    }

};
}

#endif // POINTER_H




/*

新的设计方案:
 智能指针的抽象父类
 析构函数 virtual ~Pointer() = 0;  (为什么本函数析构不是纯虚类,  因为继承的Object析构函数是纯虚类)
 重载 operator->()
 重载 operator*()

*/



SmartPointer

#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H

#include "Pointer.h"

namespace DTLib
{
    
    
template <typename T>
class SmartPointer : public Pointer<T>
{
    
    

public:
    SmartPointer(T* p = NULL) : Pointer<T>(p)
    {
    
    
    }

   /*
    SmartPointer( const SmartPointer<T>& obj)
    {
        this->m_pointer = obj.m_pointer();
        const_cast< SmartPointer<T>& >(obj).m_pointer = NULL;
    }



    // error
    //..\DTLib\/SmartPointer.h:20: error: '((const DTLib::SmartPointer<Test>*)obj)->DTLib::SmartPointer<Test>::<anonymous>.DTLib::Pointer<Test>::m_pointer' cannot be used as a function
    */


    SmartPointer<T>& operator = (const SmartPointer<T>& obj)
    {
    
    
        if( this != &obj )
        {
    
    
            T* p = this->m_pointer; // 异常安全: 先用临时变量p 保存m_pointer所指向的堆空间
            //delete m_pointer; // 不能先删除空间,有可能造成异常的抛出
            this->m_pointer = obj.m_pointer();
            const_cast< SmartPointer<T>& >(obj).m_pointer = NULL;

            delete p;
        }
        return *this;
    }


    ~SmartPointer() // 肯定需要这个析构函数,否则还是抽象类
    {
    
    
        delete this->m_pointer;
    }

};

}


#endif // SMARTPOINT_H

main.cpp

#include <iostream>
#include "SmartPointer.h"

using namespace std;
using namespace DTLib;


class Test : public Object
{
    
    
public:
    Test()
    {
    
    
        cout << "Test" <<endl;
    }

    ~Test()
    {
    
    
        cout << "~Test" <<endl;
    }
};

int main()
{
    
    

    SmartPointer<Test> sp = new Test();
    SmartPointer<Test> spn = new Test();


    return 0;
}

猜你喜欢

转载自blog.csdn.net/dashuu/article/details/115217008