From 9c8a71ef6e74b25daff9af6019f7bcfee4ca95b5 Mon Sep 17 00:00:00 2001 From: cjoan Date: Wed, 22 Mar 2017 13:04:29 -0400 Subject: [PATCH] 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 cd86cc25b60950dfd26f8f0f8840e576e0da1fc0 and 33217eb46f4bb5668cc5b763e9e428f93218545a "Clarify deallocation done by std.typecons.Unique." --- std/typecons.d | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/std/typecons.d b/std/typecons.d index 43d03b632..92f065488 100644 --- a/std/typecons.d +++ b/std/typecons.d @@ -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.