0
点赞
收藏
分享

微信扫一扫

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​​的修改应该报错.


举报

相关推荐

0 条评论