Exact effects of returning Structs

bearophile bearophileHUGS at lycos.com
Fri Aug 27 10:25:33 PDT 2010


Era Scarecrow:

>   I have some experimental code I'm writing, and it seems when i return a structure it is either corrupted, or should be disallowed all together. A postblit is suggested this(this), but since I'm returning a structure that isn't tied to anything else it doesn't need to duplicate it.

If possible please show a complete minimal program that contains a main() that shows your problem.
I have written this, but I don't see the problem:

import std.stdio: writeln, write;

enum int N = 100;

struct Foo {
    int x;
    char[] arr;
}

Foo fun2() {
    Foo f1;
    f1.arr.length = N;
    f1.arr[] = 'x';
    f1.x = 25;

    writeln(f1.arr.length);
    write(">");
    foreach(i; 0 .. N)
        write(f1.arr[i]);
    writeln("<");
    return f1;
}

void main() {
    Foo f2;
    f2 = fun2();
    writeln(f2.x);
    writeln(f2.arr.length);
    write(">");
    foreach(i; 0 .. N)
        write(f2.arr[i]);
    writeln("<");
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list