只能指针是代理模式的一种:
智能指针实现需要注意的问题:
1.构造函数指明显示构造。
2.拷贝构造函数,先断开前一个指针,然后用之前指针的值初始化现在的指针。
3.赋值函数需要先断开之前的指针,然后释放现在指针指向的内存,最后用之前的指针赋值现在的指针。
4.参数是引用,避免产生临时对象。
代码如下:
#include <iostream>
#include <string> /************************************************************************/
/* 代理模式的智能指针的实现 */
/************************************************************************/ template<typename T>
class auto_ptr
{ public:
explicit auto_ptr(T *pointer = NULL):m_pointer(pointer){}
auto_ptr(const auto_ptr<T>& rhs):m_pointer(rhs.release()){}
auto_ptr<T>& operator=(auto_ptr<T>& rhs)
{
if (this != &rhs)
{
m_pointer = reset(rhs.release());
return *this;
}
}
T& operator*(){return *m_pointer;}
T* operator->(){return m_pointer;}
T* get() const
{
return m_pointer;
}
T* release()
{
T* oldpointer = m_pointer;
m_pointer = NULL;
return oldpointer;
} void reset(T *p = NULL)
{
if (p != m_pointer)
{
delete m_pointer;
m_pointer = p;
} }
private:
T *m_pointer;
}; int main()
{ return 0;
}
延迟打开大图像
#include <iostream>
#include <string> using namespace std; class Image
{
public:
Image(string name):m_imagename(name){}
virtual void show()
{ }
protected:
string m_imagename;
}; class BigImage:public Image
{
public:
BigImage(string name):Image(name){}
virtual void show()
{
cout << m_imagename <<" show big image" <<endl;
}
};
class BigImageProxy:public Image
{
public:
BigImageProxy(string name):Image(name),m_pimage(0){}
virtual void show()
{
if (m_pimage == NULL)
{
m_pimage = new BigImage(m_imagename);
}
m_pimage->show();
}
private:
BigImage* m_pimage;
}; int main()
{
Image *pimage = new BigImageProxy("big.jpg");
pimage->show();
return 0;
}