引用计数的开销

《efficient C++》中说,C++通过开发一种称作引用计数的垃圾回收机制来控制对象的常见、清除、复制和赋值等操作,不过天下没有免费的午餐,这样做会对象创建时速度的降低。

例:创建引用计数类RCBigInt对类BigInt中的对象进行计数;RCObject提供计数的功能,被BigInt继承;RCPtr类通过重载 -> 和 * 操作符成为智能指针

///////////////////////////////////////////////////// RCObject /////////////////////////////////////////////// 
class RCObject
{
public:
 void addReference() {++refCount;}
 void removeReference() {if(--refCount==0) delete this;}
 void markUnshareable() {shareable=false;}
 bool isShareable() const {return shareable;}
 bool isShared() const {return refCount>1;}
protected:
 RCObject():refCount(0),shareable(true) {}
 RCObject(const RCObject &rhs):refCount(0),shareable(true){}
 RCObject &operator=(const RCObject& rhs) {return *this;}
 virtual~RCObject() {}
private:
 int refCount;
 bool shareable;
};
//////////////////////////////////////////////////////////// BigInt //////////////////////////////////////////////
class BigInt:public RCObject
{
 friend BigInt operator +(const BigInt &,const BigInt&);
public:
  BigInt (const char *);
  BigInt (unsigned=0);
  BigInt (const BigInt &);
  BigInt& operator= (const BigInt&);
  BigInt& operator+=(const BigInt&);
  ~BigInt();
  char *getDigits() const {return digits;}
  unsigned getNdigits() const {return ndigits;}
private:
  char *digits;
  unsigned ndigits;
  unsigned size;
  BigInt (const BigInt&,const BigInt&);
  char fetch(unsigned i) const;
};
//////////////////////////////////////////////////////////// RCPtr<T> //////////////////////////////////////////////
template<class T>
class RCPtr
{
public:
 RCPtr(T*realPtr=0):pointee (realPtr) {init();}
 RCPtr(const RCPtr& rhs):pointee(rhs.pointee){init();}
 ~RCPtr() {if(pointee) pointee->removeReference();}
 RCPtr& operator= (const RCPtr& rhs);
 T* operator->() const {return pointee;}
 T&operator* () const {return *pointee;}
private:
 T*pointee;
 void init();
};
class RCBigInt
{
friend RCBigInt operator+ (const RCBigInt&,const RCBigInt&);
public:
 RCBigInt(const char*p):value(new BigInt(p)){}
 RCBigInt(unsigned u=0):value(new BigInt(u)){}
 RCBigInt(const BigInt& bi): value(new BigInt(bi)){}

private:
 RCPtr<BigInt> value;
};

 


 创建1000000个BigInt和RCBigInt,比较它们的运行速度,即如果是悲催的:

引用计数的开销 - maryhp - 犀利の风林火山
前者3049ms,后者5967ms,大概慢了1倍。
posted @ 2017-02-26 22:20  opama  阅读(356)  评论(0编辑  收藏  举报