On Sunday, 9 January 2022 at 20:58:05 UTC, forkit wrote:
Do not understand why one line is not considered @safe, but the other is.

//----

module test;

import std;

@safe void main()
{
    immutable string[] strings = ["one", "one", "two"];

    immutable(string)*[] pointers = null;

    foreach(size_t i, ref str; strings)
    {
        if(str == "one")
        {
            //pointers ~= &str; // not allowed in @safe ??

pointers ~= &strings[i]; // for @safe, I have to revert to using an index into strings.
        }
        i++;
    }
}

//-----

Try the @trusted and in/out:

```d
auto pro(in immutable string[]   strings,
        out immutable(string)*[] pointers) @trusted {
    foreach(i, ref str; strings)
    {
        if(str == "one")
        {
            //pointers ~= &strings[i]/* ok
            pointers ~= &str;//*/
        }
        /* unnecessary:
        i++;//*/
    }
}

@safe void main()
{
    immutable string[] strings = ["one", "one", "two"];

    immutable(string)*[] pointers = null;

    strings.pro(pointers);

    assert(pointers[0] ==
           &strings[0]); // ok

    assert(pointers[1] ==
           &strings[1]); // ok

}
```

Reply via email to