d应禁止切片返回域静态数组.
类型 | 注意 |
|---|---|
ref param &pointer | checkAddresVar拒绝 |
ref param slice[] | checkAddresVar拒绝 |
ref return &pointer | 太严格 |
ref return slice[] | 太松 |
下面允许转义域指针.
// REQUIRED_ARGS -preview=dip1000
@safe:
ref int*[1] identity(ref return scope int*[1] x)
{
return x;
}
int* escape()
{
int stackVar = 0xFF;
scope int*[1] x = [&stackVar];
int*[] y = identity(x)[];
return y[0];
}
void main()
{
int* dangling = escape();
}
wb:怀疑在这一行:
域 int*[1] x = [&stackVar];
域不是可传递,允许它会导致编译器跟丢了栈地址,并允许转义.
Dennis:
x是切片是这样的,但这是1维数组,等价于:
scope int* x = &stackVar;
这是正确的.
转义已在@safe:下,加@safe来显式双检查
-dip1000真应该为默认.
wb:
多次忘记加@safe.@safe真的应该是默认值.
加-dip1000时,会删错误消息,我忽略了它.
继续先前错误:
@safe:
ref int* identity(ref return scope int* x) { return x; }
int* escape() {
int stackVar;
scope int* x = &stackVar;
int* y = identity(x);
return y;//错误:可能不会返回`y`域变量
}
接着:
@safe:
ref int*[1] identity(ref return scope int*[1] x) { return x; }
int*[1] escape() {
int stackVar;
scope int*[1] x = [&stackVar];
int*[1] y = identity(x);
return y; //错误:可能不会返回`y`域变量
}
好.
int* escape() {
int stackVar;
scope int*[1] x = [&stackVar];
int*[1] y = identity(x);
return y[0];//错误:可能不会返回`y`域变量
}
好.
int* escape() {
int stackVar;
scope int*[1] x = [&stackVar];
int*[1] y = identity(x);
int*[] z = y[]; //错误:不能取`y`本地域地址
return z[0];
}
好.这里,正确检测到y切片.但如果在身份调用后放个[]:
int* escape() {
int stackVar;
scope int*[1] x = [&stackVar];
int*[] y = identity(x)[];
return y[0];
}
无误,坏了.identity()返回值切片未正确传播其x参数的域.这是escape.d中问题.
D:
是的,域丢失了,因为无传递域,所以@safe代码中不应允许切片.
修复仅限于变量,而不是返回值
escape.d就是用来解决转义(域)的.
浙公网安备 33010602011771号