Creating a reference counted type?

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 12 07:29:19 PDT 2016


I'm wondering if it's this easy to create a reference counted 
type:

struct Foo
{
	int _refCount = 1;

	this(...)
	{
		// allocate resources, etc.
	}

	this(this)
	{
		this._refCount++;
	}

	~this()
	{
		this._refCount--;

		if (this._refCount == 0)
		{
			// free resources.
		}
	}
}

Are there any other considerations I need to handle?

Another thing that is puzzling me is that when creating an 
instance of the above struct and passing as an argument to a 
function, the copy constructor is called and the reference count 
is incremented. This is expected. However, when the function 
returns, the destructor is called (on the copy) and the reference 
count lowered. How does the original instance know of the updated 
reference count from the copy?


More information about the Digitalmars-d-learn mailing list