Has the ban on returning function nested structs been lifted?
spir
denis.spir at gmail.com
Fri Mar 18 10:19:10 PDT 2011
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.
Denis
--
_________________
vita es estrany
spir.wikidot.com
More information about the Digitalmars-d
mailing list