Dlang - 有没有办法在对象中嵌入对象?

Dlang - Is there a way to embed objects in objects?

根据 D 规范,所有 class 都是通过引用访问的,这意味着以下 class 将按如下方式在内存中布局。

伪代码:

class A
{
    public int c;
    public B b;
}

类型A对象的内存布局:

4 bytes | int c

(4/8) bytes | address of b

有没有办法创建一个 class 将 b 直接嵌入到 A 而不是引用?还是我忽略了什么?

有一些选项:

首先,您可以将 B 设为结构类型,如果您不需要 ref 语义,那么一开始就不要将其设为 class。

否则你可以使用scoped!B分配b

import std.typecons;
class A
{
    public int c;
    public scoped!B b;
}

在这两种情况下,当包含它的 A 被销毁时,将调用 B 的析构函数。

事实证明,Scoped 比我想象的要好,你也可以使用 emplace,在这种简单的情况下,它有点麻烦,但可能会派上用场:

class A {
    import std.conv;

    public  B b;

    // We can't just use sizeof here because we want the size of the
    // instance, not the reference.
    private void[__traits(classInstanceSize, B)] b_space;

    this() {
        b = emplace!B(b_space);
    }
}
上面答案中的

scoped!T 是函数,不是类型;因此,给定的示例将不起作用。原因是 classes 必须使用构造函数调用进行初始化。

作为解决方法,使用 typeof() 并在 class' 构造函数中初始化成员:

import std.typecons;
class B { }
class A {
    public int c;
    public typeof(scoped!B()) b;
    this() {
        this.b = scoped!B();
    }
}

请注意,虽然构造函数中的行看起来像一个赋值,但它被正确地解释为一个构造。