【发布时间】:2014-02-28 17:28:35
【问题描述】:
在 D 中,可以使用 scope 在堆栈上分配类,即
void foo()
{
scope example = new Bar();
}
现在,如果Foo 类有Bar 类作为成员,有没有办法将Bar 就地存储在Foo 中,并用Foo 将其拆除? p>
我希望如此
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!");
}
会产生类似的东西
酒吧
福
我是主力!
~酒吧
~Foo
相反,我只得到
Foo
我是主力!
~Foo
似乎将类成员存储为垃圾收集引用而不是原地存储只是不必要地使堆布局复杂化而没有什么好处。如果没有指定将Bar 保留在原地,那么scope 在这种情况下会做什么?
【问题讨论】:
标签: memory-management reference d object-lifetime