dip1000 and preview in combine to cause extra safety errors

12345swordy alexanderheistermann at gmail.com
Wed Jun 8 19:33:26 UTC 2022


On Wednesday, 8 June 2022 at 19:07:00 UTC, Meta wrote:
> On Wednesday, 8 June 2022 at 18:44:28 UTC, 12345swordy wrote:
>> On Wednesday, 8 June 2022 at 18:32:41 UTC, Timon Gehr wrote:
>>> [...]
>>
>> I got to say here, you shouldn't be able to compile that code 
>> at all if it is going to shoot you in the foot unintentionally.
>>
>> - Alex
>
> I believe this is because foo is not annotated with @safe, thus 
> it's @system by default and you're allowed to do all kinds of 
> unsafe things. Mark it @safe and the compiler will correctly 
> complain:
>
> ```
> @safe
> string foo(in string s)
> {
>     return s; // Error: scope variable `s` may not be returned
> }
>
> void main()
> {
>     import std.stdio;
>     string[] result;
>     foreach(c; "hello")
>     {
>         result ~= foo([c]);
>     }
>     writeln(result);
> }
> ```
>
> In addition, changing `in` to `const return scope` makes the 
> compiler aware that you intend to return the value, and thus it 
> seems to somehow know not to re-use that stack space, and 
> correctly prints ["h", "e", "l", "l", "o"].

You shouldn't have to mark your functions safe to prevent 
shooting yourself in the foot. It should give a warning message 
that can be surpass by explicitly marking your function as system.

-Alex


More information about the Digitalmars-d mailing list