@trusted and return ref
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 24 16:12:40 PST 2015
On Tuesday, 24 February 2015 at 22:37:58 UTC, Ola Fosheim Grøstad
wrote:
> 1. My understanding is that @trusted is supposed to give memory
> safety escapes by providing a context which reestablish a
> memory safety context on return.
Yep, that's how I got it, too. A @trusted function is supposed to
be memory-safe.
> Yet in this thread
> http://forum.dlang.org/thread/mcik3j$153g$1@digitalmars.com it
> is stated that this paradigm is an example of «careful use of
> @trusted»:
>
> count = (() @trusted => cast(uint*) malloc(uint.sizeof))();
> …arbitrary code…
> (() @trusted => free(count))();
>
> They way I see it, this is equivalent to typing a
> reinterpret_casting malloc and free as memorysafe operations in
> isolation, basically providing a malloc!int() and free() as
> memory safe functions.
Yep. "Careful use": You have be careful when you (ab)use @trusted
like this.
The idea is that the compiler enforces safety for the rest of the
code. You have to be cautious about the effects of the @trusted
malloc/free, but the compiler checks the other stuff. If the
whole function was @trusted, the compiler wouldn't catch other
safety violations that are not related to malloc/free.
The downside is that @safe on that function then doesn't mean
"compiler verified memory-safe" anymore. Instead it means
"compiler assisted @trusted".
There's also the other way around: Mark the function as @trusted
and throw ()@safe{...}() covers over the non-problematic parts.
This doesn't work when a template parameter affects the safety,
though.
> But why is malloc and free not considered safe by default then?
Well, because they aren't.
> These @trusted functions clearly cannot prevent leaks within
> their own context. You would need a @trusted-only storage class
> on the receiving pointer to do that and a @trusted move type.
>
> If this is careful use of @trusted, then I don't see the point
> of having @trusted at all. What is the purpose? What is it
> meant to cover? In order for @trusted to make sense in this
> code segment ( http://dpaste.dzfl.pl/f3d854feede9 ) I would say
> that the whole class will have to be marked @trusted. Is that
> possible?
The goal is to have human verified, compiler recognized
memory-safety, when E allows for it.
You can't:
* mark nothing @safe/@trusted, because malloc/free are not safe;
* mark the methods @trusted, because E may be unsafe.
@trusted malloc/free is a hack, but it allows the compiler to
infer @safe iff E is safe.
More information about the Digitalmars-d-learn
mailing list