what are const scope parameters?

Jason House jason.james.house at gmail.com
Fri Mar 7 20:19:02 PST 2008


Denton Cockburn wrote:

> On Fri, 07 Mar 2008 21:09:45 -0500, Jason House wrote:
> 
>> Denton Cockburn wrote:
>> 
>>> [quoted text muted]
>> 
>> I believe the difference is that in your first case x can't be kept past
>> the function lifetime and in the second case, a copy of x can be kept.
> 
> 
> That's what I used to think, but look at this in D2:
> 
> import std.stdio;
> 
> class C
> {
> int x;
> }
> 
> 
> // with in and const, neither function can change the parameter
> C foo(in C c)
> {
> C d = new C;
> d.x = c.x;
> writefln("foo.d.x = ", d.x);
> 
> return cast(C)c; // yes, we've casted away the const
> }
> 
> C bar(const C c)
> {
> C d = new C;
> d.x = c.x; // we've made use of c
> writefln("bar.d.x = ", d.x);
> 
> return cast(C)c;
> }
> 
> void main()
> {
> C c = new C;
> c.x = 5;
> C c2 = foo(c);
> c = bar(c2); // CLEARLY c2 is still alive here, so what has scope done?
> 
> writefln(c.x);
> }
> 
> both styles work (the same apparently).  So what did the scope part of the
> in (which is equal to 'const scope') accomplish?

cast at your own risk ;)
Having c2 still alive in main after the call to bar is ok and expected.  The
idea is that bar can't keep it but gives no restrictions on the caller. 
The cast that breaks this stuff is your fault ;)


More information about the Digitalmars-d-learn mailing list