[Dlang-study] [lifetime] Few root decisions to take on RC classes

Michel Fortin michel.fortin at michelf.ca
Sun Nov 1 14:04:35 PST 2015


Le 1 nov. 2015 à 9:02, Andrei Alexandrescu <andrei at erdani.com> a écrit :

> Agreed. We need to put weak pointers in the initial DIP and carry them through.

It might be good enough to simply make sure someone can create them as a library type. But for that you need to add a way to have the compiler *not* do automatic reference counting inside the implementation of the weak pointer. A @manualrc attribute you could attach to a function to simply disable automatic insertion of opInc/opDec in that function would probably be all that's really needed.

That being said, while I guess it's okay, a library implementation using a struct will suffer some of the same problems Rebindable has.


> Regarding opInc/opDec, here are some rules that the compiler may use:
> 
> * Both are callable with an unsigned integer, 1 by default
> * opInc(n) followed by opDec(n) against the same object, with no call to isUniquelyReferenced in between, may be removed

"isUniquelyReferenced" is not a special case. Any function that can mutate the lvalue you are passing as an argument is in the same boat. In other words, you can only elide the opInc/opDec pair if you can prove that the function won't change the object referenced by that lvalue during its execution.


> * opInc(n1) followed by opInc(n2) against the same object may be replaced with opInc(n1 + n2)
> * opDec(n1) followed by opDec(n2) against the same object may be replaced with opDec(n1 + n2)

That's fine in theory, but it's better to avoid doing it this way if you can. Keep in mind that for many RC systems the cost will be proportional to the integer you provide. If for instance I was to implement opInc for COM objects I'd have to write it like this:

	void opInc(int n) {
		while (n--) AddRef(); // n virtual calls, n atomic increments
	}

So ideally the compiler should always use the smallest "n" possible.


-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca




More information about the Dlang-study mailing list