confusion about structs

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 25 15:05:09 PDT 2011


On Sunday, September 25, 2011 23:40:36 Christian Köstlin wrote:
> I have this small program, which does some data handling with structs:
> 
> struct App {
>    private int[] fData;
>    this(size_t initialSize) {
>      fData = new int[initialSize];
>    }
>    void put(int i) {
>      fData[0] = i;
>    }
>    int[] get() {
>      return fData;
>    }
> }
> 
> struct Builder {
>    int i;
>    App app = App(2);
>    this(int i_) {
>      i = i_;
> //    app = App(2);
>    }
>    void put(int v) {
>      app.put(v);
>    }
>    int[] get() {
>      return app.get();
>    }
> }
> 
> int[] get(int i) {
>    auto b = Builder(i);
>    b.put(i);
>    return b.get();
> }
> 
> 
> unittest {
> 
>    auto h1 = get(1);
>    auto h2 = get(2);
>    assert(h1[0] == 1);
>    assert(h2[0] == 2);
> }
> 
> int main(string[] args) {
>    return 0;
> }
> 
> compiling this with dmd -unittest shows, that the tests are failing.
> if you comment in the line //    app = App(2); then the tests work as
> expected.
> Could you please explain what struct Builder { App app = App(2); } does
> exactly compared to doing thins in the structs constructor?

It's a bug, but I don't know if it's that what you're trying to do doesn't 
work or that it isn't illegal. When you directly initialize a member variable, 
that initialization happens at compile time. The value of app in Builder.init 
is what app is directly initialized to. So, if you set the value of app in the 
constructor to the same value that it was set to at compile time, it should 
result in the same value for app.

The problem is that App has a dynamic array in it, and that's allocated on the 
heap. Arrays can be used in CTFE, but I don't know if the same array allocated 
in CTFE can then be used at runtime. If it can, then there's a bug here, 
because app = App(2) in the constructor shouldn't be necessary. If it can't, 
then directly initializing an App at compile time shouldn't compile in the 
first place.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list