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 @ 2022-08-16 10:23  zjh6  阅读(15)  评论(0)    收藏  举报  来源