in / out for C++ programmers

Ali Çehreli acehreli at yahoo.com
Sat Mar 24 00:02:58 PDT 2012


On 03/23/2012 11:50 PM, Jonathan M Davis wrote:
 > On Friday, March 23, 2012 23:37:27 Ali Çehreli wrote:
 >> 'in' is the same as 'const scope'. const part is easy to understand but
 >> I don't know what 'scope' does. I could not understand what the spec
 >> means with "references in the parameter cannot be escaped (e.g. assigned
 >> to a global variable)" for scope:
 >>
 >>     http://dlang.org/function.html
 >
 > You mean that you don't understand what it means for a reference to 
escape a
 > function?

No. I've known that for decades now. I don't understand it because I've 
tried what I've understood about scope in code examples and could not 
see any difference.

Also, I don't understand the semantics of it. For example, 'const' is 
welcoming: it says "I accept mutable and immutable references as 
parameters." (Because it is a guarantee that it will not modify.) 
'immutable' is restricting: "I accept only immutable references."

What is 'scope' on a parameter? Is that a guarantee or a requirement on 
the argument?

 > In the case of scope, it means that what you pass in cannot be 
assigned to a
 > global or static variable, and it cannot be returned from that 
function. So,
 > for instance.
 >
 > int[] foo(const int[] a)
 > {
 >      ...
 > }
 >
 > could not assign a to a global or static variable and cannot return it.

Yet this compiles:

int[] g;

int[] foo(scope int[] slice)
{
     g = slice;
     return slice;
}

void main()
{
     int[] slice;
     int[] result = foo(slice);
}

The funny thing is, what does function have to do the scope of a 
parameter that is passed to it? Since it's an argument passed from the 
outside it may be scoped or dynamic.

And that's why I don't understand it. :) I suspect scope is a remnant 
from the D1 days. (?)

 > This
 > can allow some additional optimizations as well as improve safety in some
 > cases. For instance, if you pass
 >
 > int[5] b;
 >
 > to foo, then you know that no slice of that static array will escape, 
since
 > something like
 >
 > int[] bar()
 > {
 >      int[5] c;
 >      return c;
 > }
 >
 > is just as bad as the case with&a. I believe that scope is used primarily
 > with delegates however (particularly, since you often _want_ to be 
able to
 > return a slice of an array passed to a function).

Fine, delegates... Is that a guarantee or a requirement in that context?

 > It guarantees that the the
 > delegate's context won't escape the function and can make it so that the
 > delegate's context doesn't have to be allocated on the heap, which 
improves
 > efficiency.
 >
 > scope is pointless with types which aren't pointers or references though.
 >
 > - Jonathan M Davis

Ali



More information about the Digitalmars-d-learn mailing list