Refcounting smart pointer?

Sönke Ludwig ludwig_no at spam_informatik.uni-luebeck.de
Wed Sep 3 13:39:43 PDT 2008


Bill Baxter schrieb:
> Has anyone made a reference counting smart pointer using D2 structs yet?
> It should be possible now with the opDot, destructors, postblit thingy
> and constructor.
> 
> Is anything missing to make it work?  Actually I don't even think the
> constructor was necessary.  So someone probably could have done this a
> while ago.
> 
> --bb

Just implemented this today, and it seems to work fine:

struct CountedRef(T) {
	static if( is(T == class) ){
		alias T T_ref;
	} else {
		alias T* T_ref;
	}

	private {
		T_ref m_object;
		int* m_refcount;
	}

	this(T_ref obj){
		m_object = obj;
		m_refcount = new int;
		*m_refcount = 1;
	}

	~this(){
		if( m_refcount && --(*m_refcount) <= 0 ){
			delete m_object;
			delete m_refcount;
		}
	}

	this(this){
		if( m_refcount )
			(*m_refcount)++;
	}

	T_ref get(){ return m_object; }
	const(T_ref) get() const { return m_object; }

	T_ref opDot(){ return m_object; }
	const(T_ref) opDot() const { return m_object; }
}

struct IntrusiveCountedRef(T) {
	static if( is(T == class) ){
		alias T T_ref;
	} else {
		alias T* T_ref;
	}

	private {
		T_ref m_object;
	}

	this(T_ref obj){
		m_object = obj;
		obj.addRef();
	}

	~this(){
		if( m_object )
			m_object.releaseRef();
	}

	this(this){
		if( m_object )
			m_object.addRef();
	}

	T_ref get(){ return m_object; }
	const(T_ref) get() const { return m_object; }

	T_ref opDot(){ return m_object; }
	const(T_ref) opDot() const { return m_object; }
}



More information about the Digitalmars-d mailing list