dip1000区间副本

原文

ref int f(ref return scope int* p) @safe
  { 
    return *p;
  }

引用+中域编译,保护p值,而非p地址,成功编译,因为p就是返回值.
而:

ref int f(ref scope return int* p) @safe
  { 
    return *p;
}

编译失败.不能返回p域变量.行为由函数签名,而非返回表达式决定.
问题是代码试图存储域保护的int*p到未受保护*ptr有效负载指针中.而dip1000不可能完成.
dip1000的全部意义在于,可在@safe代码中使用栈分配的数组.
返回ref转换为指针并解引用来取非区间值.

// 用-preview=dip1000编译.
@safe:
struct Arr
{
    int** ptr;

    ref int* index() return scope {
        return *ptr;
    }

    void assign(int* p) scope {
        *ptr = p;
    }
}

void main()
{
    scope Arr a;

    a.assign(*&a.index());

    auto tmp = &a.index();
    a.assign(*tmp);
}
posted @ 2022-10-09 15:10  zjh6  阅读(23)  评论(0)    收藏  举报  来源