Has the ban on returning function nested structs been lifted?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Mar 18 11:21:11 PDT 2011
On Friday, March 18, 2011 10:19:10 spir wrote:
> On 03/18/2011 06:05 PM, Andrej Mitrovic wrote:
> > 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;
>
> Great magic auto is. Auto with you be.
Yeah. Actually, Andrei has been making changes to std.range and std.algorithm so
that _most_ functions which return new range types work this way. So, if TDPL
says that it's illegal, it probably needs to be changed. Either that or we need
to stop switching over to doing things that way. On the whole though, it strikes
me as a positive change.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list