d@safe中允许创建内部指针

原文
垃集规范提到,结构中具有内部指针未定义行为.
@safe代码中禁止未定义行为,但允许创建内部指针,而这可能会破坏dip1000:

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

    this(int dummy) {
         ptr = &storage;
    }

    int* get() return scope {
        return ptr;
    }
}

int* escape() {
    S s = S(0);
    return s.get; // s栈变量指针逃逸.
}

错误消息不是很好,但它正确识别了问题.

ptr = &storage;

*is*获取this地址,并赋值给了this,在storage*(this+0),ptr*(this+8).
thisthis有更长生命期?添加return scope到构造函数时,仍然有效.

@safe:
struct S {
    int storage;
    int* ptr;

    this(int dummy) return scope {//加了`中域`.
         ptr = &storage;
    }

    int* get() return scope {
        return ptr;
    }
}

int* escape() {
    S s = S(0);
    return s.get; // s栈变量指针逃逸.
}

没关系,它说this的生命期比"this变量地址"长,但是,它应在测试套件中,且带return scope的修改应该报错.

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