Should modifying private members be @system?

ag0aep6g anonymous at
Fri Oct 4 13:40:28 UTC 2019

On Friday, 4 October 2019 at 12:34:46 UTC, Dennis wrote:
> In this case it's a member function. A common pattern is to put 
> unsafe parts of a function in a block like this:
> () @trusted {/*do something unsafe*/} ()
> Such a lambda cannot be @trusted unconditionally, it's trusted 
> because it is known it can only be called in its context and 
> not outside the outer function's scope.

Being pedantic, if the safety of the nested function relies on 
its surroundings, then it can't be @trusted. It may be a common 
pattern, but it's undermining @safe anyway.

> My broader question is whether the language can be designed so 
> member functions can rely on certain assumptions. Currently 
> writing proper @trusted code is extremely hard because it is 
> unknown what you can work with.

Agreed that writing @trusted code is hard.

> - does const give any guarantees? (afaik, yes)

Yes. It guarantees that the value won't change through the const 
reference. As far as I understand, you can rely on that in 
@trusted code. You can also rely on `immutable` data not ever 
changing (after creation).

The flipside is that you can't break those guarantees in 
@trusted/@system code. The compiler will allow it, but you must 
take care not to mutate const/immutable values. Same with other 

> - does pure give any guarantees? (no, you can return 
> `cast(size_t) (new int)`)

Yeah, you can't rely on two identical calls giving the same 

`pure` pretty much just means "doesn't touch globals, at least 
not visibly". So here:

int x;
void f(const int* a) pure;
void main() { f(&x); }

It's guaranteed that the call to f doesn't change x. Without 
`pure`, it might.

> - does private give any guarantees? (currently not, but it 
> could)

I don't think `private` guarantees anything with regards to 
safety. Even when `__traits(getMember, ...)` and `.tupleof` and 
other low-level mechanisms would respect `private`, you still 
couldn't rely on it for safety. You can't trust the current 
module/struct/class any more than other code.

> So with @system members, can we give any guarantees of 
> integrity to member functions?

You'd have the guarantee that no @safe code can mess with the 

You'd still have to make sure that all the @system and @trusted 
code plays nice with each other, but that's just how it is with 
non- at safe code.

That is, some other @system/@trusted function could set an 
invalid _length in your struct. And then your opIndex would 
violate safety. But that would just be a bug in that other 
function then.

More information about the Digitalmars-d mailing list