const, final, scope function parameters

Regan Heath regan at netmail.co.nz
Wed May 30 08:00:50 PDT 2007


Bruno Medeiros Wrote:
> Regan Heath wrote:
> > 
> > 'scope' poses no performance problems as it doesn't change the existing behaviour, it is actually just a formalisation of existing behaviour.  Take this example:
> > 
> > class A { ..large object, lots of members.. }
> > void foo(A b) {}
> > A a = new A();
> > foo(a);
> > 
> > when foo is called a copy of the reference 'a' is made and it is called 'b'.  It is 'scope' because it exists solely in the function scope, once the function returns 'b' ceases to exist (because it was a copy of 'a' on the stack and the stack is reclaimed at function exit).
> > 
> > This is what currently happens in D, and is what happens in C and C++ too. 'scope' is intended to detact and prevent this:
> > 
> > A* pa;
> > void foo(A b) { pa = &b; }
> > 
> > In the above pa is set to the address of the reference 'b', this address becomes invalid when 'foo' returns and thus violates 'scope'.  Likewise this:
> > 
> > A* foo(A b) { return &b; }
> > 
> > will be caught and prevented.
> > 
> > This above code is currently valid D and the compiler gives no errors, once 'scope' is added to D the compiler will detect this and give an error.
> > 
> 
> It should be noted however that it is not the value of b that is 
> intrisincally 'scope'. It is the value of &b that is scope. The same 
> happens with any local variable, parameter or not.

True, which is why I look at 'scope' as less of a "new feature" and more of a "formalisation" of what actually happens plus some help from the compiler at finding and preventing bugs related to it.

In a sense all variables at whatever level are 'scope', that is to say they exist within a given scope (program, class, function) and cease to exist above/outside that scope.

Also as you say, it's the address of them, rather than their value which is what becomes invalid when execution leaves their scope.

Regan



More information about the Digitalmars-d mailing list