在D中,对象是否可以在内部保存成员对象?

Mat*_*ine 5 memory-management d reference object-lifetime

在D中,可以使用scope,即,在堆栈上分配类

void foo()
{
    scope example = new Bar();
}
Run Code Online (Sandbox Code Playgroud)

现在,如果类Foo具有类Bar作为成员,是否有任何方法可以Bar在内部存储Foo并使用Foola C++进行拆分?

我曾希望如此

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!");
}
Run Code Online (Sandbox Code Playgroud)

会产生类似的东西

Bar
Foo
我是主角!
~Bar
~Foo

相反,我只能得到

Foo
我是主力!
〜富

看起来将类成员存储为垃圾收集引用而不是就地存储只是不必要地使堆布局复杂化而没有什么好处.什么是scope做在这种情况下,如果不指定举行Bar就地?

Mih*_*uns 5

不要使用范围类.这些都被有效地弃用,并且只是过去的遗产.有一个Phobos助手可以达到类似的效果.你重写的例子:

import std.stdio;
import std.typecons;

alias ScopedBar = typeof(scoped!Bar());

class Bar {

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

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

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

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

    ScopedBar inside;
}

void main()
{
    writeln("Main before scope");
    {
        auto f = scoped!Foo();
    }
    writeln("Main after scope");
}
Run Code Online (Sandbox Code Playgroud)