文章引用: 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
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<T>& operator = (const SmartPointer<T>& obj)
{
if( this != &obj )
{
T* p = this->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
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;
}