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

【c++】智能指针

2015-06-05 20:50 645 查看
// vc下的智能指针,重点在于拥有权的转移

#include <iostream>
using namespace std;

template<class Type>
class Autoptr
{
public:
Autoptr(int *p = NULL) :ptr(p), owns(ptr != NULL)
{}
Autoptr(const Autoptr<Type> &t) :ptr(t.release()), owns(t.owns)
{}
Autoptr<Type>& operator=(const Autoptr<Type> &t)
{
if (this != &t)// 判断是否给自己赋值
{
if (ptr != t.ptr)// 判断是否指向同一个空间
{
if (owns)// 如果有拥有权,则释放当前空间
{
delete ptr;
}
else
{
owns = t.owns;// 反之,得到拥有权
}
ptr = t.release();// 让t失去拥有权
}
}
return *this;
}
~Autoptr()
{
if (owns)
delete ptr;
}
public:
Type& operator*()const
{
return (*get());
}
Type* operator->()const
{
return get();
}
Type* get()const
{
return ptr;
}
Type* release()const
{
((Autoptr<Type> *const)this)->owns = false;
return ptr;
}
private:
bool owns;
Type *ptr;
};

int main()
{
int *p = new int(10);
Autoptr<int> pa(p);
cout << *pa << endl;
Autoptr<int> pa1(pa);
cout << *pa1 << endl;
int *p1 = new int(100);
Autoptr<int> pa2(p1);
Autoptr<int> pa3;
pa3 = pa2;
cout << *pa3 << endl;
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: