what are const scope parameters?

Denton Cockburn diboss at hotmail.com
Fri Mar 7 19:15:32 PST 2008


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?


More information about the Digitalmars-d-learn mailing list