Clarify deallocation done by typecons.RefCounted.

I had trouble understanding how RefCounted!T was supposed to help me manage resources.  These document changes should clarify the process and make it easier for others to understand.

This is follow-up after this post on the D learn forum: https://forum.dlang.org/post/qctmkqpqnreysxcjmrgm@forum.dlang.org
and after commits cd86cc25b6 and 33217eb46f "Clarify deallocation done by std.typecons.Unique."
This commit is contained in:
cjoan 2017-03-22 13:04:29 -04:00 committed by GitHub
parent 5105f45801
commit 9c8a71ef6e

View file

@ -5121,9 +5121,28 @@ enum RefCountedAutoInitialize
/**
Defines a reference-counted object containing a $(D T) value as
payload. $(D RefCounted) keeps track of all references of an object,
and when the reference count goes down to zero, frees the underlying
store. $(D RefCounted) uses $(D malloc) and $(D free) for operation.
payload.
$(D RefCounted) is implemented as a pointer to a data structure, which
is refered to as the $(I store) or $(I storage implentation struct) in
this documentation. The store contains a reference count and the
$(D T) payload. $(D RefCounted) uses $(D malloc) to allocate the
store. As instances of $(D RefCounted) are copied or go out of scope,
they will automatically increment or decrement the reference count on
the store that they point to. When the reference count goes down to
zero, $(D RefCounted) will call $(D destroy) against the payload and
call $(D free) to deallocate the store. If the $(D T) payload contains
any references to GC-allocated memory, then $(RefCounted) will add it
to the GC memory that is scanned for pointers, and remove it from GC
scanning before $(D free) is called on the store.
One important consequence of $(D destroy) is that it will call the
destructor of the $(D T) payload. GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
$(D T), such as file handles or pointers to $(D malloc) memory, will
still be valid during the destructor call. This allows the $(D T) to
deallocate or clean up any non-GC resources immediately after the
reference count has reached zero.
$(D RefCounted) is unsafe and should be used with care. No references
to the payload should be escaped outside the $(D RefCounted) object.