Newbie initial comments on D language - scope
Janice Caron
caron800 at googlemail.com
Tue Feb 5 23:51:50 PST 2008
On 06/02/2008, Janice Caron <caron800 at googlemail.com> wrote:
>
> You're right. That was a mistake. I meant
>
> > atomic { if (--pa->refCount == 0) delete pa; }
> > atomic { ++pb->refCount; }
>
And just to be really clear, real code would need extra checks, above
and beyond the simplified version I wrote above. In fact, it would be
more like
if (pa != null && pa->refCount != 0)
{
if (pb != null && pb->refCount != 0)
{
atomic { ++pb->refCount; }
atomic { if (--pa->refCount == 0) delete pa; }
etc. It's important to do the increment before the decrement because
otherwise you run the risk of crashing if (pa == pb). And if you store
refCount in too small a variable, you also would need to be concerned
about ++pb->refCount wrapping. Microsoft VC++'s implementation of
std::string, for example, contains a one-byte reference count, and
they have some complicated code in there which interprets 0xFF
differently so that things don't fall over.
But that's using your suggested convention that (refCount == 0)
implies "not reference counted". In my real life implementation,
ref-countedness was a compile-time property, not a runtime property,
so I didn't have to do all of those tests. I think compile-time
ref-countedness is a very good idea, and has many fantastic
advantages. I just think it's a very bad idea to make it a runtime
property.
More information about the Digitalmars-d
mailing list