I've been bitten again by my lack of understanding of the D struct lifecycle :-/. I managed to reduce my buggy program to the following example:

[code]
import std.stdio;

struct Foo
{
    @disable this();
    @disable this(this);

    this(int valueIn) {value = valueIn;}
    ~this() {writeln("Foo being destroyed: ", value);}

    int value;
}

struct FooList
{
    @disable this();
    @disable this(this);

    this(int)
    {
        writeln("Before 8");
        foos[0] = Foo(8);
        writeln("Before 1");
        foos[1] = Foo(1);
        writeln("Before 2");
        foos[2] = Foo(2);
        writeln("Before 3");
        foos[3] = Foo(3);
        writeln("After Foo construction");
    }

    Foo[5] foos;
}

unittest
{
    auto fooList = FooList(0);
    writeln("About to lose scope");
}
[/code]

[output]
Before 8
Before 1
Foo being destroyed: 0
Before 2
Foo being destroyed: 0
Before 3
Foo being destroyed: 0
After Foo construction
About to lose scope
Foo being destroyed: 0
Foo being destroyed: 3
Foo being destroyed: 2
Foo being destroyed: 1
Foo being destroyed: 8
[/output]

There are a few things which confuse me about this:
* Why does this code compile? In particular, I would have expected that with Foo[5] but initialization for only Foos 0 .. 3 and with the @disabled constructors in Foo, there would be a compiler error. * Where do those first three destroyed Foos come from? I thought there should have been no Foos existing since default construction is @disabled... * Even if somehow the Foos are being created despite the @disabled default constructor, why are only three Foos being destroyed before the scope is lost?

So I guess what I'm wondering is:
* If I @disable a default constructor on a struct, does the language guarantee that I won't have default-constructed instances of that struct? If not, what is the point of @disable for default constructors? If so, is the above situation a compiler bug or something I am missing? * Is the below the right general syntax for creating an instance of a struct so as to avoid creating more than one copy? If not, what is?

Stack variable: auto foo = Foo(5);
Member variable: Foo m_foo; this(/* args */) {m_foo = Foo(5);}

Thanks!

Reply via email to