@safe question

Paul Backus snarwin at gmail.com
Tue Jan 11 21:50:00 UTC 2022


On Tuesday, 11 January 2022 at 21:38:58 UTC, forkit wrote:
> On Tuesday, 11 January 2022 at 14:54:51 UTC, Paul Backus wrote:
>> ..
>> If you compile with -preview=dip1000, the compiler will 
>> actually keep track of which pointers point to stack memory, 
>> and will allow your original code. But -preview=dip1000 is 
>> still somewhat experimental, and the documentation for it is 
>> pretty sparse, so you may have an easier time just working 
>> around the limitations of the default safety checks.
>
> Thanks. Appreciate the explanation :-)
>
> In the end though, correct code should just compile.
>
> I shouldn't need a 'work around' :-(

In any statically typed language, there is always going to be 
code which you, the programmer, know is correct, but which the 
compiler can't automatically prove is correct. The same is true 
for safety.

If you know a particular bit of code is memory safe, but the 
compiler can't prove it, you can mark that code as @trusted. For 
example:

     () @trusted { pointers ~= &str; )();

This example uses an immediately-invoked function literal [1] 
(also known as a "lambda") to apply the @trusted attribute to a 
single statement.

Of course, when you write @trusted code, you must be *very* sure 
that what you are doing cannot possibly lead to undefined 
behavior, no matter what happens in other parts of the program. 
There's a post on the official D blog, "How to Write @trusted 
Code in D," [2] that talks about some of the most common 
pitfalls, and gives advice for avoiding them.

[1] https://dlang.org/spec/expression.html#function_literals
[2] 
https://dlang.org/blog/2016/09/28/how-to-write-trusted-code-in-d/


More information about the Digitalmars-d-learn mailing list