d这里为什么不@安全

原文

pointers ~= &str; //为何@安全中禁止
pointers ~= &strings[i]; // 而这里又可以呢?

@safe代码中禁止局部变量地址,只要在函数体内声明,即使堆分配串变量引用,也算局部变量.因而禁止.
原代码在此:

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; // 禁止.
            pointers ~= &strings[i]; // 用索引串.
        }
        i++;
    }
}
posted @ 2022-01-10 14:37  zjh6  阅读(15)  评论(0)    收藏  举报  来源