我正在尝试实例化一个充满独特资源的容器,以确保当容器被销毁时,容器管理(拥有)的所有项目也立即自动被销毁。
以下(非唯一)代码按预期运行。请注意 Foo 对象在应用程序退出之前不会被销毁(GC 最终会回收它们)。暂时忽略 GC,通过在 DList 被销毁时不确定地销毁它们——在“退出范围”消息中——容器中的对象在应用程序的生命周期内有效地泄漏:
import std.stdio,
std.container,
std.range,
std.typecons,
std.random;
class Foo
{
this()
{
debug( List ) writefln( " %s constructor invoked", this.classinfo.name );
}
~this()
{
debug( List ) writefln( " %s destructor invoked", this.classinfo.name );
}
}
int main( string[] args ) {
debug( List ) writeln( "main():" );
{
debug( List ) writeln( " entering scope" );
scope auto list = DList!( Foo )();
immutable ELEMENTS_TO_MAKE = 5;
for( auto i = 0; i < ELEMENTS_TO_MAKE; ++i )
{
Foo foo = new Foo();
list.insertBack( foo );
}
debug( List ) writefln( " Length: %s elements in container", walkLength( list[] ) );
debug( List ) writeln( " exiting scope" );
}
debug( List ) writeln( " exiting app" );
return 0;
}
正如预期的那样,给出以下输出:
main():
entering scope
main.Foo constructor invoked
main.Foo constructor invoked
main.Foo constructor invoked
main.Foo constructor invoked
main.Foo constructor invoked
Length: 5 elements in container
exiting scope
exiting app
main.Foo destructor invoked
main.Foo destructor invoked
main.Foo destructor invoked
main.Foo destructor invoked
main.Foo destructor invoked
但是当我更新应用程序以使用 Unique's 时,事情就崩溃了:
...
int main( string[] args ) {
debug( List ) writeln( "main():" );
{
debug( List ) writeln( " entering scope" );
scope auto list = DList!( Unique!Foo )();
immutable ELEMENTS_TO_MAKE = 5;
for( auto i = 0; i < ELEMENTS_TO_MAKE; ++i )
{
Unique!Foo foo = new Foo();
list.insertBack( foo.release ); //looks like Phobos containers can't hold Unique's??? :(
}
debug( List ) writefln( " Length: %s elements in container", walkLength( list[] ) );
debug( List ) writeln( " exiting scope" );
}
debug( List ) writeln( " exiting app" );
return 0;
}
上面的代码给出了以下输出:
main():
entering scope
main.Foo constructor invoked
main.Foo destructor invoked
Bus error: 10
注释掉 list.insertBack() 行可以消除总线错误 10。关于如何自动和确定性地销毁容器拥有的对象有什么想法吗?