d按域标记析构器

原文

C c;
class C {
    ~this() @safe {
        c = this;
    }
}

这是可以接受的,但不安全.我建议始终按"域"标记析构器
赋值类引用给另一个类引用是安全的.我同意

除非赋值垃圾,更详细的不安全示例:

import std.stdio: writeln;
import core.memory: GC;
C c;
class C
{
    immutable int* ip;
    this(int x) @safe { this.ip = new int(x); }
    ~this() @safe { c = this; }
}
void main() @safe
{
    () { new C(42); } ();
    () { ubyte[1000] clear_stack; } ();
    () @trusted { GC.collect(); } ();
    immutable int* ip = c.ip;
    writeln(*ip); /* 打印"42". */
    new int(13);
    int should_still_be_42 = *ip;
    writeln(should_still_be_42); /* 打印"13" 修改了不变数据. */
}

我意思是用标记带@safe的析构器.这样不会有副作用.

会有副作用.如,在结构上,标记析构器为会阻止返回此结构实例.
更谨慎措施是标记逃逸析构器为@system(即,使原代码成为编译时错误)

不,它仅限制析构器函数体,而不限制析构器调用者.
-dip1000编译它:

@safe:

struct S
{
    ~this() scope {}
    void* p;
}

S test()
{
    S s;
     //错误:可能不会返回s域变量
    return s;
}

void main()
{
}

这像是旧dip1000设计的错误/残余
这里引入.

修复.因此,现在应该很清楚了,要按"域"标记析构器.

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