您的位置:首页 > 编程语言 > C语言/C++

C++ 泛型指针 auto_ptr

2010-05-04 00:38 281 查看
Code:

#include <iostream>

using namespace std;

template <class T>

class myauto_ptr

{

public :

explicit myauto_ptr(T *p = 0) throw()

:m_ptr(p) {}

myauto_ptr(myauto_ptr<T> ©) throw()

:m_ptr(copy.release()) {}

myauto_ptr<T>& operator=(myauto_ptr<T> &other) throw()

{

if (this != &other)

{

delete m_ptr;

m_ptr = other.release();

}

return *this;

}

~myauto_ptr() { delete m_ptr;}

T& operator*() const throw() { return *m_ptr; }

T* operator->() const throw() { return m_ptr; }

T* get() const throw() { return m_ptr; }

void reset(T *p = 0) throw()

{

if (m_ptr != p)

{

delete m_ptr;

m_ptr = p;

}

}

T* release() throw()

{

T *temp = m_ptr;

delete m_ptr;

//m_ptr = 0; //省掉这句会有什么效果???

return temp;

}

private:

T *m_ptr;

};

int main()

{

myauto_ptr<int> pi(new int(1024));

cout <<"pi:" << *pi << endl;

myauto_ptr<int> pi1(pi);

cout << "pi:" << *pi << endl;

myauto_ptr<int> pi2(new int(2048));

cout << *pi2 << endl;

if (pi.get())

*pi = 1024;

else

pi.reset(new int(1024));

cout << *pi << endl;

return EXIT_SUCCESS;

}

第一次发表笔记,这是泛型指针的实现,属于异常安全的

但是不能用于STL泛型容器中,因为其copy 构造和赋值操作具有破坏性,不符合STL泛型容器的要求

但也可以修改myauto_ptr的copy construct 和 copy assignment,使其符合STL泛型容器的要求,但存在危险
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: