Idea #1 on integrating RC with GC
luka8088
luka8088 at owave.net
Thu Feb 6 00:28:35 PST 2014
On 5.2.2014. 0:51, Andrei Alexandrescu wrote:
> Consider we add a library slice type called RCSlice!T. It would have the
> same primitives as T[] but would use reference counting through and
> through. When the last reference count is gone, the buffer underlying
> the slice is freed. The underlying allocator will be the GC allocator.
>
> Now, what if someone doesn't care about the whole RC thing and aims at
> convenience? There would be a method .toGC that just detaches the slice
> and disables the reference counter (e.g. by setting it to uint.max/2 or
> whatever).
>
> Then people who want reference counting say
>
> auto x = fun();
>
> and those who don't care say:
>
> auto x = fun().toGC();
>
>
> Destroy.
>
> Andrei
Here is a thought:
Let's say we have class A and class B, and class A accepts references to
B as children:
class A {
B child1;
B child2;
B child3;
}
I think that the ultimate goal is to allow the user to choose between
kinds of memory management, especially between automatic and manual. The
problem here is that class A needs to be aware whether memory management
is manual or automatic. And it seems to me that a new type qualifier is
a way to go:
class A {
garbageCollected(B) child1;
referenceCounted(B) child2;
manualMemory(B) child3;
}
Now suppose we want to have only one child but we want to support
compatibility with other kinds of memory management:
class A {
manualMemory(B) child;
this (B newChild) {
child = newChild.toManualMemory();
}
this (referenceCounted(B) newChild) {
child = newChild.toManualMemory();
}
this (manualMemory(B) newChild) {
child = newChild;
}
~this () {
delete child;
}
}
This way we could write code that supports multiple models, and let the
user choose which one to use. The this that I would like to point out is
that this suggestion would work with existing code as garbageCollected
memory management model would be a default:
auto b = new B();
auto a = new A(b);
Another thing to note is that in this way a garbage collector would know
that we now have two references to one object (instance of class B). One
is variable b and another is child in object a. And because of the
notation garbage collector is aware that if could free this object when
variable b goes out of scope but it should not do it because there is a
still a manually managed reference to that object.
I am sure that there are many more possible loopholes but maybe it will
give someone a better idea :)
More information about the Digitalmars-d
mailing list