More radical ideas about gc and reference counting

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Sun May 11 22:57:34 PDT 2014


Am Sun, 11 May 2014 17:50:25 -0700
schrieb Walter Bright <newshound2 at digitalmars.com>:

> As long as those pointers don't escape. Am I right in that one cannot store a 
> borrowed pointer into a global data structure?

Right, and that's the point and entirely positive-to-do™.
Your general purpose function does not know how the memory was
allocated, that it receives a pointer to. In particular it
must not assume that it is safe to keep a reference to it as
there are several memory management schemes that are
incompatible with that, like reference counting or stack
allocations.

Expanding on these two, Rust can now safely use _more_
allocation schemes with functions that take borrowed pointers
than is safely possible in D!

RC pointers:
You cannot pass them as raw pointers in D. In Rust they can
be passed as borrowed.

Stack pointers:
Not allowed in D in @safe code and inherently unsafe in
@system code. Again this is safe to do in Rust due to
borrowing.

> The similarity is that there are 
> one way conversions from one to the other, and one of the types is more general. 
> I infer from your other statements about Rust that it doesn't actually have a 
> general pointer type.

Yes it does:
http://static.rust-lang.org/doc/0.10/guide-unsafe.html#raw-pointers

But the design principle in Rust is to only have them in
@system code (speaking in D terms), in particular to interface
with C.

Turning the argument back to D and assuming you wrote a
function that takes a raw pointer because you plan to store it
in a global variable. How do you make sure you get a pointer
to something with infinite life-time? Let me answer this: You
either use GC pointers exclusively or you rely on the
convention that the function takes ownership of the memory.
The former is impractical and the latter cannot be statically
enforced.

Borrowed pointers add an @safe way to deal with the situation
in all contexts where you don't need to store a reference.
But if you _do_ need that capability: ask explicitly for GC
pointers as they can guarantee unlimited life-time.
If that's still too restrictive mark it @system and use raw
pointers (in Rust: unsafe keyword).

Finally, this is not Rust vs. D, because D has had borrowed
pointer function arguments since ages as well - maybe even
longer than Rust. The semantics of "in/scope" were just never
fully implemented. Once this is done we can also write:

@safe void main()
{
	auto stack = 42;
	foo(&stack);
}

@safe void foo(scope int*);

-- 
Marco



More information about the Digitalmars-d mailing list