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?

Reply via email to