DIP74
Title: | Safe Reference Counted Class Objects |
---|---|
DIP: | 74 |
Version: | 1 |
Status: | Concept |
Created: | 2015-02-23 |
Last Modified: | 2015-02-26 |
Author: | Walter Bright and Andrei Alexandrescu |
Abstract
This DIP proposes @safe reference counted class objects for D (including exceptions).
Description
DIP25 allows defining struct types that own data and expose references to it, @safely, whilst controlling lifetime of that data. This proposal allows defining class objects that are safe yet use deterministic destruction for themselves and resources they own.
The compiler detects automatically and treats specially all classes and interfaces that define the following two methods:
class Widget {
ulong AddRef();
ulong Release();
...
}
The methods may or may not be final or inherited. Any attributes are allowed on these methods. They must be public. If these two methods are accessible, the compiler categorizes this class type as a reference counted class and treats it as follows:
- Whenever a new reference to an object is created, compiler inserts an implicit call to AddRef. Call is inserted only if the reference is not null. There is no call inserted for the first reference created via a constructor.
- Whenever a reference to an object goes out of scope, compiler inserts an implicit call to Release. Call is inserted only if the reference is not null.
- Implicit conversion to supertypes (class or interface) is allowed ONLY if the supertype also is a reference counted type. It follows that reference counted types cannot be converted to Object (unless Object itself defines the two methods).
- Typechecking methods of reference counted types is done the same as for structs. This is important because it limits what reference counted types. Consider:
class Widget1 {
private int data;
ref int getData() { return data; } // fine
...
}
class Widget2 {
private int data;
ref int getData1() { return data; } // ERROR
ref int getData2() return { return data; } // fine
ulong AddRef();
ulong Release();
...
}
Defining a reference counted class
TODO
class Widget {
ulong AddRef();
ulong Release();
...
}
Copyright
This document has been placed in the Public Domain.