d类中之类

原文

import std.stdio;
import std.typecons;

alias ScopedBar = typeof(scoped!Bar());
//域bar.

class Bar {
    this() { writeln("Bar"); }
    ~this() { writeln("~Bar"); }
};

class Foo
{   
    this()
    {
        this.inside = scoped!Bar();//
        writeln("Foo");
    }
    ~this() { writeln("~Foo"); }
    ScopedBar inside;//ScopedBar
}

void main()
{
    writeln("Main before scope");
    {
        auto f = scoped!Foo();
    }
    writeln("Main after scope");
}

如下当bar是构的,是成立的:

import std.stdio;

class Foo {
    this() { writeln("Foo"); }

    ~this() { writeln("~Foo"); }

    scope Bar inside;
}

class Bar {

    this() { writeln("Bar"); }

    ~this() { writeln("~Bar"); }
};

void main()
{
    scope f = new Foo();
    writeln("I'm a main!");
}

类在中原位分配:

import std.stdio;

class Bar {
    this() { writeln("Bar"); }
    ~this() { writeln("~Bar"); }
}


class Foo {
    this() {
        writeln("Foo");
        inside = InPlace!Bar.getDefault();
    }//外部构建构

    ~this() { writeln("~Foo"); }

    // 原位
    InPlace!Bar inside;
}

struct InPlace(T) {
    // 原位缓冲
    private byte[__traits(classInstanceSize, T)] rawData;

    @property T obj() { return cast(T) rawData.ptr; }
    alias obj this; // 小心,不要逃逸引用
    @disable this(); // 使用点强制初化.

    // 默认构造
    static InPlace!T getDefault() {
        InPlace!T t = void;
        t.initializeObject();
        t.obj.__ctor();
        return t;
    }

    void initializeObject() {
        assert(__traits(classInstanceSize, T) == 8);
        assert(T.classinfo.init.length == 8);
        assert(this.rawData.length == 8);
        this.rawData[] = T.classinfo.init[];
    }

    // 带参构造
    this(T...)(T t) {
        initializeObject();
        obj._ctor(t);
    }
    ~this() {
        .destroy(obj); // 构中调用析构器.
    }
}

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