On Tuesday, 11 January 2022 at 10:57:28 UTC, forkit wrote:
On Monday, 10 January 2022 at 03:21:46 UTC, Paul Backus wrote:

Taking the address of a local variable is forbidden in @safe code. Even though str is a ref variable that points to a heap-allocated string, it is still considered a local variable because it is declared inside the body of a function.

but strings[] is also a local variable declared in the body of the same function, and yet within the foreach statement, @safe lets me do:

pointers ~= &strings[i]; // safe

...but not this below, where str is just a reference to the exact same memory as the statement above... is it not? How is this below any more or less safe than the above statement.

pointers ~= &str;  // not safe - ok, but why??

Because the compiler doesn't look at that much context, and it's possible to write code where `str` points to memory that's on the stack; for example:

    string[3] strings = ["foo", "bar", "baz"];
    foreach (ref str; strings) {
        // ...
    }

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.

Reply via email to