Has the ban on returning function nested structs been lifted?

Andrej Mitrovic none at none.none
Fri Mar 18 10:05:19 PDT 2011


>From TDPL, page 263:
"Nested struct objects cannot be returned from functions because the caller doesn't have access to their type".

However auto seems to work around this limitation:

module structInFunction;

import std.stdio;
void main()
{
    auto local = foo(0);
    assert(local.sum() == 30);
    writeln(typeid(local));     // structInFunction.foo.Local
}

auto foo(int a)
{
    int z = a + 10;

    struct Local
    {
        int x;
        int y;

        int sum()
        {
            return x + y + z;
        }
    }

    return Local(10, 10);
}

I don't have a use case for this, personally. But it does seem to work.

Well, almost. The following issues a runtime error:
module structInFunction;

import std.stdio;
void main()
{
    auto local = foo(0);
    writeln(local.sum());
    assert(local.sum() == 30);
    writeln(typeid(local));     // structInFunction.foo.Local
}
auto foo(int a)
{
    int z = a + 10;
    struct Local
    {
        int x = 10;
        int y = 10;

        int sum()
        {
            return x + y + z;
        }
    }
    Local local;
    return local;
}

object.Error: Access Violation

An explicit call to the ctor like this works with no runtime errors:
    auto local = Local();
    return local;


More information about the Digitalmars-d mailing list