d手动析构可能违反内存安全
析构器
的目的是描述对象
生命期结束
时的清理工作.允许@safe
代码在该点前手动调用析构器
,然后继续用析构对象
会破坏RAII
内存管理:
module app;
import core.stdc.stdlib : malloc, free;
struct UniqueInt {
private int* target;
this(const(bool) doCreate) scope @trusted nothrow @nogc {
target = cast(int*) malloc(int.sizeof);
*target = 5;
}
@disable this(this);
@disable this(ref typeof(this));
@disable ref typeof(this) opAssign(ref typeof(this));
void withBorrow(void delegate(scope int*) @safe action) @safe {
action(target); }
~this() scope @trusted nothrow @nogc {
if(target !is null) {
free(target);
target = null;
}
}
}
//
UniqueInt unique;
shared static this() {
unique = true; }
void main() @safe {
import std.stdio: writeln;
unique.withBorrow((scope int* borrowed) @safe {
writeln(*borrowed);
destroy(unique);
writeln(*borrowed); // 释放后使用
});
}
我认为合理解决方案是:不管~this()
属性如何,使调用__dtor,__xdtor
或手动析构
为@system
操作.
为了在安全
函数中自动创建T类型对象,T
的析构器必须是安全的或受信任
的.
目前析构器由__dtor
成员函数体现,即析构器声明
的属性与生成的__dtor
成员函数的属性相同.
有些类型
需要定义析构器
来做不安全的事情,主要是释放
对象内仔细限制
的内存.
这产生了以下难题:
1
.如果类型
使析构器为@trusted
,则表明安全
代码也可自由地手动调用__dtor()
.后续用此类对象就会破坏安全
.
2
.如果类型
选择用@system
析构器,则安全代码无法创建这类对象
.
乍一看,需要一种方法告诉编译器"仅在隐式调用析构器
时,是可信任的".
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现