const, final, scope function parameters

Robert Fraser fraserofthenight at gmail.com
Tue May 29 09:10:10 PDT 2007


I understand that part, but I don't necessarily want to reassign the reference, just change something in the state of the object being referred to. For example:

struct Foo
{
    int x;
}

void bar(in Foo var)
{
    var.x = 10;
}

Allowed?

Regan Heath Wrote:

> Denton Cockburn Wrote:
> > On Mon, 28 May 2007 18:56:00 -0400, Robert Fraser wrote:
> > 
> > > Ah, thanks, now I understand scope (I understood the other two; I thought scope would prevent copies of references). Still, const by default seems a bit odd - make it explicit. For example, if a file stream is being passed to a function, could I write to it inside the function if it was const?
> > > 
> > 
> > No, not if it changes the internals of the object.
> > If you want that, then simply specify the parameter as 'ref'
> > 
> > void foo(ref Stream x) { ...blah... }
> > or
> > void foo(scope final Stream x) { ...blah... }
> > 
> > I'm trying to understand this too, so hopefully I didn't just tell you the
> > wrong thing.
> 
> You're answer looks good to me.  
> 
> Passing with 'ref' means that the Stream 'x' is _not_ a copy of the passed reference, but is actually the exact reference passed.  This is useful when you might want to re-assign it inside the function and expect that change to be reflected outside the function.
> 
> Passing with 'scope final' gives a copy of the passed reference, 'final' prevents/detects you from reassigning it (catching the bug where you want the change to be reflected and actually meant to use 'ref' and preventing the bug where a parameter is re-used several times in a large function and this can result in bugs due to programmers expecting it to have it's inital value).  'scope' prevents/detects any attempt to store it's address in an external variable (which would be an ugly bug to find) because as a copy it ceases to exist after the function returns.
> 
> I'm just re-iterating the behaviour for anyone still coming to grips with this.  A good understanding of what goes on in the background (function agruments being copies, or not, etc) makes for better programmers.
> 
> Regan




More information about the Digitalmars-d mailing list