[Issue 19183] DIP1000 defeated if auto used instead of scope in variable declaration with template this member function

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Aug 21 19:20:48 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=19183

--- Comment #5 from ag0aep6g <ag0aep6g at gmail.com> ---
(In reply to Atila Neves from comment #4)
> I made a mistake when I posted the code. This compiles but shouldn't (the
> only difference is removing `scope` from the destructor). 
[...]
> @safe:
> 
> const(int)* gInts;
> 
> void main() {
>     auto s = MyStruct(10);
>     gInts = s.ints;
> }
> 
> struct MyStruct
> {
>     import core.stdc.stdlib;
>     int* ints;
>     this(int size) @trusted { ints = cast(int*) malloc(size); }
>     ~this() { () @trusted { free(ints); }(); }
>     scope ptr(this This)() { return ints; }
> }

You're not calling `ptr`. `main` reads the `ints` field directly. That's
allowed, of course. D has no way of preventing @safe code from accessing a
local struct's field.

If the code is changed to actually call `ptr`, it still compiles. Maybe that
shouldn't be allowed, but it's not obvious to me from the code. If this is a
safety violation, we should be able to show something like memory corruption,
mutating immutable data, stuff like that.

As it is, the only obvious safety violation is in the @trusted destructor. It
assumes that the `ints` field is not accessible from @safe code, but that's
wrong. Unfortunately, misusing @trusted like that is necessary for stuff like
this, but it still means breaking the @trusted promise. The consequence is that
(at least) the whole module must be checked manually to uphold the assumption
of the badly @trusted method. One cannot rely on @safe to catch mistakes in
that area. So if none of MyStruct's methods can be allowed to return `ints`,
because the destructor relies on that, then that must be checked manually.

--


More information about the Digitalmars-d-bugs mailing list