I wrote a simple article about an extended scope
attribute that manages pointers and types that contains indirections:
https://github.com/Loara/Rethink_scope_in_D/blob/main/README.md
I called this new attribute rscope
(this is a temporary name, I'll change it in future in order to avoid misunderstandings), any variable or function parameter marked as rscope
can be referenced only by other variables that are also rscope
:
rscope int i = 1;
int j = i; //ok, doesn't share references
//ref int k = i; error: k holds a reference to i
rscope ref int h = i; //ok, both rscope
rscope int *ip = new int (3);
//int *iq = ip; error: reference sharing
int *ik = new int(*ip); //ok
//rscope *ih = ik; error: ik is not rscope, see the link
struct A{
int a;
int *b;
}
rscope A a = {1, &i}; //ok, i rscope
//A b = a; //error, A has indirections, a rscoped but b no
Also you can use labelled rscope
in order to avoid to share references between two or more rscope
variables:
rscope(A) int *a = ...;
rscope(A) int *b = a;//ok
//rscope(B) int *c = a; error: different rscope groups
Why and where use this new attribute? Everywhere you need to avoid references escape:
-
when dealing with unsafe casts:
class A{...} ... const A a = ... ... rscope{//every variable declared inside this block is automatically rscope A a_unsafe = cast(A) a; //now you can use a_unsafe inside this block ... } //Now any reference to a_unsafe should be expired
-
inside a
synchronized
block:shared int i; Mutex mutex; .... synchronized(mutex){ rscope{ rscope ref int i_ref = get_rscoped_ref!int(i); .... } }
If you think these features would be interesting I'll write a new DIP and propose it, so I'm waiting your feedbacks.