d应禁止切片返回域静态数组.

地址
参考
无传递,所以禁止取域变量地址

类型注意
ref param &pointercheckAddresVar拒绝
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就是用来解决转义(域)的.

posted @   zjh6  阅读(11)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示