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).
this比this有更长生命期?添加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的修改应该报错.
浙公网安备 33010602011771号