More Effective C++之引用计数(二)

2014-11-24 13:20:06 · 作者: · 浏览: 33
ewT(*oldValue);
   }
   counter->AddReference();
  }
  void makeCopy()
  {
   if (counter->isShared())
   {
    T* oldValue = counter->pointee;
    counter->RemoveReference();
    counter = newCountHolder;
    counter->pointee = newT(*oldValue);
    counter->AddReference();
   }
  }
 };
 class Widget
 {
  public:
   Widget(intSize){}
   Widget(constWidget& rhs){}
   ~Widget(){}
   Widget operator=(const Widget& rhs){}
   void doThis(){printf("doThis() ");return;}
   int showThat() const{printf("showThat() "); return 0;}
  protected:
  private:
   inti;
 };

 class RCWidget
 {
  public:
   RCWidget(intsize):value(newWidget(size)){}
   void doThis(){value->doThis();}
   int showThat()const {returnvalue->showThat();}
  protected:
  private:
   RCIPtr value;
};
   评估

  实现引用计数是需要有前提的,不是所有的情况下,使用引用计数都是合适的。适合情况如下:

  相对多的对象共享相对少量的实值。

  对象的实值产生或者销毁的成本很高,或者占用很多内存。

  但是要记住,即使是Java也会有内存泄漏,不要指望小小的引用计数(上面简单的实现)不会产生同样的问题。

  引用计数是一项很深奥的技术,想想Java,所以需要很谨慎的对待,但愿它能带来程序设计上的优化。