Reference counting allows for a constant cost with predictable lifetime ownership patterns. This is quite often used with system resources or in times when neither scope ownership nor GC are accecptable memory allocation or lifetime schemes. By adding it into the language, further improvements may be possible including for read only types.
Atomic mutation of counters is quite expensive as the mutation and access invalidates the cpu cache. This has been shown in real world scenarios to have significant impact on a programs performance https://pkolaczk.github.io/server-slower-than-a-laptop/
Due to this, D needs to solidfy the existing pattern of reference counting operations into the language so that they may be seperated out from construction and destruction of a given type. Seperating out from construction/destruction allows for future optimizations and memory rules that are specific to reference counting while maintaining correctness.
Adds two new operator overloads opRefAdd
and opRefSub
.
These two methods are used as a replacement for copy constructors/postblit and destructors on a struct for handling of reference counting.
Adding a reference occurs when a copy or a move of a struct or a class reference occurs.
Removing a reference occurs when a scope ends for a given variable or a setting of a variable.
If a pair of reference adding and subtraction occur in any order on a given object, the compiler may elide both the calls if it can prove it is the same object. This has the benefit of making reference counting potentially very cheap and future contributions of const based reference counting being possible.