Janu. 11

 

// use counted handle class for the T hierarchy
template <typename T>
class Handle {
public:
// default constructor: unbound handle
Handle(): p(0), use(new std::size_t(1)) { }
// attaches a handle to a copy of the T object
//Handle(const T& ref): p(new T(ref)), use(new std::size_t(1)) { }
//  class T need define virtual function clone
Handle(const T& ref): p(ref.clone()), use(new std::size_t(1)) { }
// copy control members to manage the use count and pointers
Handle(const Handle &i):
p(i.p), use(i.use) { 
++*use; 
}
~Handle() { 
decr_use(); 
}
Handle& operator=(const Handle& rhs) {
++*rhs.use;
decr_use();
p = rhs.p;
use = rhs.use;
return *this;
}
// member access operators
const T *operator->() const { 
if (p) 
return p;
else 
throw std::logic_error("unbound handle"); 
}
const T &operator*() const { 
if (p) 
return *p;
else 
throw std::logic_error("unbound handle"); 
}
private:
T *p;        // pointer to shared item
std::size_t *use;    // pointer to shared use count
// called by both destructor and assignment operator to free pointers
void decr_use()
if (--*use == 0) { 
delete p; 
delete use; 
}
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章