日期:2011-03-22 13:55:00 来源:本站整理
More Effective C++之引用计数[VC/C++编程]
本文“More Effective C++之引用计数[VC/C++编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
Reference counting让我想起了Java,当假如想用C++来实现Java的本领的话,那Reference counting必不可少.Reference counting可以节俭程序的运行本钱,大量的构造、析构、分配、释放和拷贝的代价被省略.
实现
classRCObject
{
public:
RCObject():refCount(0),shareable(true){}
RCObject(constRCObject&):refCount(0),shareable(true){}
RCObject& operator=(constRCObject& rhs){return *this;}
virtual ~RCObject()=0;
void AddReference(){++refCount;}
void RemoveReference(){if (--refCount == 0) deletethis;}
void markUnshareable(){shareable = false;}
bool isShareable() const{returnshareable;}
bool isShared() const {returnrefCount > 1;}
private:
int refCount;
bool shareable;
};
RCObject::~RCObject(){}
template <classT>
class RCPtr
{
public:
RCPtr(T* realPtr = 0):pointee(realPtr){init();}
RCPtr(constRCPtr& rhs):pointee(rhs.pointee){init();}
~RCPtr(){if (pointee) pointee->RemoveReference();}
RCPtr& operator = (constRCPtr& rhs)
{
if (pointee!=rhs.pointee)
{
if (pointee)
pointee->RemoveReference();
pointee = rhs.pointee;
init();
}
return *this;
}
T* operator->() const { returnpointee;}
T& operator*() const{return *pointee;}
private:
T* pointee;
void init()
{
if (pointee == 0)
return;
if (pointee->isShareable() == false)
pointee = newT(*pointee);
pointee->AddReference();
}
};
class String
{
public:
String(const char* value = ""):value(newStringValue(value)){}
const char& operator[](intnIndex) const
{
return value->data[nIndex];
}
char& operator[](intnIndex)
{
if (value->isShared())
value = newStringValue(value->data);
value->markUnshareable();
returnvalue->data[nIndex];
}
protected:
private:
struct StringValue:publicRCObject
{
char* data;
String Value(constchar* initValue)
{
init(initValue);
}
String Value(constStringValue& rhs)
{
init(rhs.data);
}
void init(constchar * initValue)
{
data = newchar[strlen(initValue) + 1];
strcpy(data,initValue);
}
~String Value()
{
delete [] data;
}
};
RCPtr<StringValue> value;
};
这是Meyers给出的String的实现,但是我的概念是假如没有分外的必要的话,对stirng最好不要利用引用计数,因为在多线程程序中同步的代价要大于引用计数本身的好处,得不偿失.
以上是“More Effective C++之引用计数[VC/C++编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |
评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论