原文 垃集规范提到,结构
中具有内部指针
是未定义
行为.
@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
的修改应该报错.