您的位置:首页 > 其它

自己实现简单的智能指针

2016-08-04 19:40 295 查看
#include<string>
#include<iostream>
using namespace std;
template<class T>
class share
{
public:
share():point(0){}
share(T* p1)
{
point = p1;
}
~share()
{
cout << "begin to delete share" << endl;
if(NULL != point)
{
delete point;
point = NULL;
}
}
share(share& t2)
{
point = t2.point;
t2.point = NULL;
}
share& operator =(share& t2)
{
point = t2.p2;
t2.point = NULL;
return *this;

}
T* operator ->()
{
return point;
}
private:
T* point;
};

class A
{
public:
A()
{
n = 0;
}
int n;
char v[4];

};

int main()
{
share<A>sp(new(std::nothrow) A());
sp->n = 10;

share<A>sp2 = sp;
cout << "sp2->n is :" << sp2->n << endl;
return 0;
}

输出如下:

[root@237 code]# ./a.out
sp2->n is :10
begin to delete share
begin to delete share


总结:

   1、这种模式是资源独占的,当share<A>sp2 = sp后,不允许sp再用了,因为此时sp->point == NULL。--这种智能指针相当于std::auto_ptr;

有时会有疑问,既然是因为:sp->point == NULL 导致sp不能用,那在 operator =()函数中,不将‘t2.point = NULL;’不就可以了。别忘了,这样在析构时,sp跟sp2的point指向

同一块内存,而sp->point != sp2->point(指针的数值不等,但是却只想同一块内存),所以会重复释放内存。

   2、为了防止sp=sp2后,再用sp2,可以禁止  拷贝构造函数与赋值运算符。这样就相当于boost::scope_ptr了。

二、可以看出上面的智能指针并不好用,所以为了解决智能指针之间既能复制又能让不同的指针对象对同一块内存操作,引出了用引用计数的智能指针

    (就是boost::share_ptr),代码如下:

#include<string>
#include<iostream>
using namespace std;
template<class T>
class share
{
public:
share():point(0),pcount = new int(0){}
share(T* p1)
{
point = p1;
if (pcount == NULL)
{
pcount = new int(1);
}
}
~share()
{
//cout << "begin to delete share" << endl;
if(--(*pcount) == 0)
{
delete point;
delete pcount;
pcount = NULL;
cout << "begin to delete share" << endl;
point = NULL;
}
}
share(share& t2)
{
point = t2.point;
t2.(*pcount)++;
pcount =  t2.pcount;
}
share& operator =(share& t2)
{
if (--(*pcount) == 0)
{
delete point;
}
point = t2.point;
t2.(*pcount)++;
pcount =  t2.pcount;
return *this;
}
T* operator ->()
{
return point;
}
private:
T* point;
int* pcount; //应用计数一定是要所有的该类对象共用的  //这个引用计数在多线程下是不安全的。参考boost源码,应该用:<span style="color: rgb(36, 39, 41); font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 15px; line-height: 19.5px;">boost::detail::atomic_count</span>
};

class A
{
public:
A()
{
n = 0;
}
int n;
char v[4];

};

int main()
{
share<A>sp(new(std::nothrow) A());
sp->n = 10;
cout << "sp->n is :" << sp->n << endl;
share<A>sp2 = sp;
sp2->n = 20;
cout << "sp->n is :" << sp2->n << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: