+ void incref() { if(counts) ++counts->count; }
+ void decref();
+};
+
+
+template<typename T>
+class WeakPtr
+{
+ template<typename U> friend class RefPtr;
+ template<typename U> friend class WeakPtr;
+
+private:
+ T *data = 0;
+ RefCounts *counts = 0;
+
+public:
+ WeakPtr() { }
+private:
+ WeakPtr(T *d, RefCounts *c): data(d), counts(d ? c : 0) { incref(); }
+
+public:
+ WeakPtr(const WeakPtr &p): data(p.get()), counts(data ? p.counts : 0) { incref(); }
+
+ template<typename U>
+ WeakPtr(const WeakPtr<U> &p): data(p.get()), counts(data ? p.counts : 0) { incref(); }
+
+ template<typename U>
+ WeakPtr(const RefPtr<U> &p): data(p.data), counts(p.counts) { incref(); }
+
+ WeakPtr &operator=(const WeakPtr &p) { return assign(p); }
+
+ template<typename U>
+ WeakPtr &operator=(const WeakPtr<U> &p) { return assign(p); }
+
+ template<typename U>
+ WeakPtr &operator=(const RefPtr<U> &p) { return assign(WeakPtr(p)); }
+
+private:
+ template<typename U>
+ WeakPtr &assign(const WeakPtr<U> &);
+
+ T *get() const { return (counts && counts->count ? data : 0); }
+ void incref() { if(counts) ++counts->weak_count; }
+ void decref();
+};
+
+
+template<typename T>
+RefPtr<T> &RefPtr<T>::operator=(T *d)
+{
+ decref();
+ data = d;
+ counts = (d ? new RefCounts : 0);
+ incref();
+ return *this;
+}
+
+template<typename T>
+template<typename U>
+RefPtr<T> &RefPtr<T>::assign(const RefPtr<U> &p)
+{
+ decref();
+ data = p.data;
+ counts = p.counts;
+ incref();
+ return *this;
+}
+
+template<typename T>
+T *RefPtr<T>::release()
+{
+ T *d = data;
+ data = 0;
+ decref();
+ counts = 0;
+ return d;
+}
+
+template<typename T>
+void RefPtr<T>::decref()
+{
+ if(!counts) return;
+ --counts->count;
+ if(!counts->count)