Return by 'ref' problems...

Jacob Carlborg doob at me.com
Fri May 4 02:52:07 PDT 2012


On 2012-05-04 10:38, Manu wrote:
> So here's some problems.
>
> I use 'const ref' to pass structs to functions (note: because 'in ref'
> doesn't seem to work)
> And I often need to return structs by ref too, but I'm having problems:
>
> void test( const ref Thing x ) {} // this works fine. note, 'const ref'
> works fine here (in lieu of 'in ref')
>
>
> struct Thing { }
> Thing thing;
>
> const ref Thing func() { return gThing; }

In this case the function "func" is declared const and not the return 
type. The reason for this is to allow this:

class Foo
{
     const:

     // All methods will be const
}

It's possible to do this with all attributes.

> This syntax complains, but it's precisely the same expression I use to
> pass an argument in to a function, and it's fine there:
>    remedy\modules\hud.d(35):Error: function remedy.hud.func without
> 'this' cannot be const/immutable
>
> const ref Thing function() blah = &func;

Again this declares the variable const and not the return type. I'm not 
sure about the "ref" thing. I don't know if function pointers can return 
by reference, at least not the syntax.

> I need to take a pointer to this function, but It complains when I
> declare a 'function' of this type:
>    remedy\modules\hud.d(36):Error: variable remedy.hud.blah only
> parameters or foreach declarations can be ref   (... what? it works for
> parameters?)
>
>
> I try rearranging the syntax to make the first issue stop complaining:
>
> ref const(Thing) func2() { return gThing; } // this seems to work now,
> but i don't like the inconsistency...
> ref const(Thing) function() blah2 = &func;

This is the correct syntax to declare that it returns a const object.

> Error: variable remedy.hud.blah2 only parameters or foreach declarations
> can be ref

Don't know about the reference.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list