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泛型容器的要求,但存在危险
#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泛型容器的要求,但存在危险
相关文章推荐
- C++:auto_ptr智能指针的用法
- C++智能指针auto_ptr源码完全解析---以微软auto_ptr为例来探讨auto_ptr的用法
- C++中的智能指针(auto_ptr)
- [转]C++智能指针(auto_ptr)详解
- c++ 模板学习笔记:类模板模拟auto_ptr智能指针(权哥)
- c++中的智能指针auto_ptr
- C++智能指针:auto_ptr、shared_ptr、weak_ptr等
- C++ auto_ptr智能指针的用法
- C++ - 智能指针 Vs. auto_ptr
- 探究c++智能指针中auto_ptr_ref的存在意义
- C++ auto_ptr智能指针的用法
- C++智能指针--auto_ptr指针
- [C++][STL]智能指针:auto_ptr
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- C++ auto_ptr 智能指针
- C++智能指针auto_ptr(一)
- 以对象管理资源——C++智能指针auto_ptr简介
- 【C/C++】智能指针auto_ptr,share_ptr,unique_ptr
- c++智能指针auto_ptr的实现
- C++ auto_ptr智能指针的用法