Amazing110
智能指针
#include
<
iostream
>
using
namespace
std;
template
<
class
T
>
class
RefObject
{
public
:
explicit
RefObject(T
*
obj) : m_object(obj), m_ref_number(
1
)
{ }
~
RefObject()
{
DecreaseReference();
}
void
IncreaseReference()
{
m_ref_number
++
;
}
void
DecreaseReference()
{
if
(
--
m_ref_number
==
0
)
{
Destroy();
}
}
T
*
getPtr()
{
return
m_object;
}
const
unsigned
int
getReferenceNum()
{
return
m_ref_number;
}
/**/
////////////
//
private
:
void
Destroy()
{
delete m_object;
m_object
=
NULL;
m_ref_number
=
0
;
delete
this
;
}
//
Do need to implment those two function, but need declear them
//
here to avoid compiler generate them automatically.
RefObject(
const
RefObject
&
obj);
RefObject
<
T
>&
operator
=
(
const
RefObject
&
obj);
private
:
T
*
m_object;
unsigned
int
m_ref_number;
}
;
/**/
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
template
<
class
T
>
class
SmartPointer
{
public
:
//
Constructor without param
SmartPointer() : m_pRefObject(NULL)
{ }
//
Constructor with param, Do set as "explicit" to
//
avoid type chansferred automatically.
explicit
SmartPointer(T
*
T_ptr)
{
m_pRefObject
=
new
RefObject
<
T
>
(T_ptr);
}
//
In this function, we just need to decrease the reference number
~
SmartPointer()
{
if
(m_pRefObject)
{
m_pRefObject
->
DecreaseReference();
}
}
//
In copying constructor function, we need to increase the number of reference
SmartPointer(
const
SmartPointer
&
rhs) : m_pRefObject(rhs)
{
m_pRefObject
->
IncreaseReference();
}
//
Overload operator =
const
SmartPointer
<
T
>&
operator
=
(
const
SmartPointer
&
other)
{
//
We much check if other is this self
if
(m_pRefObject
==
other.m_pRefObject)
{
return
*
this
;
}
else
{
m_pRefObject
=
other.m_pRefObject;
m_pRefObject
->
IncreaseReference();
return
*
this
;
}
}
//
Overload operator*
T
&
operator
*
()
{
return
*
(m_pRefObject
->
getPtr());
}
//
Overload operator*, so "SmartPointer->" is same as "T->" now.
T
*
operator
->
()
{
return
m_pRefObject
->
getPtr();
}
protected
:
RefObject
<
T
>*
m_pRefObject;
}
;
void
main()
{
int
*
ptr1,
*
ptr2,
*
ptr3;
{
ptr1
=
new
int
(
99
);
//
If comment following code, the cout outside of this block will be not mess.
SmartPointer
<
int
>
sp1(ptr1);
cout
<<
"
The value of smart pointer is:
"
<<*
sp1
<<
endl;
}
cout
<<
"
The value of smart pointer is:
"
<<*
ptr1
<<
endl;
}
posted on 2011-09-30 12:16
天人雨
阅读(170)
评论(0)
编辑
收藏
引用
只有注册用户
登录
后才能发表评论。
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
网站导航:
博客园
IT新闻
BlogJava
知识库
博问
管理
导航
C++博客
首页
新随笔
联系
聚合
管理
统计
随笔 - 2
文章 - 0
评论 - 0
引用 - 0
常用链接
我的随笔
我的评论
我参与的随笔
留言簿
给我留言
查看公开留言
查看私人留言
随笔档案
2011年11月 (1)
2011年9月 (1)
搜索
最新评论
阅读排行榜
1. 配接器、萃取器、分配器、迭代器--STL的精髓(1204)
2. 智能指针(170)
评论排行榜
1. 智能指针(0)
2. 配接器、萃取器、分配器、迭代器--STL的精髓(0)
Powered by:
C++博客
Copyright © 天人雨