I'm trying to instantiate a container full of Unique resources, in an attempt to ensure that when the container is destroyed, all items managed (owned) by the container are also destroyed, automatically and right then.
The following (non-Unique) code behaves as expected. Notice the Foo objects aren't being destroyed until the app exits (the GC would have reclaimed them eventually). Ignoring the GC for the moment, by not destroying them deterministically at the time the DList is destroyed--at the "exiting scope" message--the objects in the container have effectively leaked for the duration of the app's lifetime:
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;
}
Gives the following output, as expected:
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
But when I update the app to work with Unique's, things fall apart:
...
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;
}
The above code gives the following output:
main():
entering scope
main.Foo constructor invoked
main.Foo destructor invoked
Bus error: 10
Commenting out the list.insertBack() line silences the Bus error 10. Any thoughts on how I can get automatic and deterministic destruction of my container-owned objects?