dip1000区间副本
原创
©著作权归作者所有:来自51CTO博客作者fqbqrr的原创作品,请联系作者获取转载授权,否则将追究法律责任
原文
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);
}