"heap" syntax
Johan Granberg
lijat.meREM at OVEgmail.com
Wed Aug 30 11:50:42 PDT 2006
Russ Lewis wrote:
> I mentioned this idea in the "future of lambda delegates" thread, but
> don't know if anybody noticed. I'm starting a new thread for discussion.
>
> The problem at hand was how to declare that a stack frame should reside
> on the heap instead of on the stack. Somebody mentioned that we could
> put *some* of the variables on the heap, which lead me to this idea:
>
> int delegate() foo() {
> int x,y,z; // these varaibles are on the stack
>
> heap { // all variables declared inside this block are on the heap!
> int a = x+y+z;
> return delegate int() { return a++; }
> // this is ok to return, since its 'this' pointer points to
> // the heap, not the stack.
> }
> }
>
> Implementation-wise, my thought is that the language automatically
> allocates a region on the stack large enough for any variables in the
> heap{} block. The stack frame then has a pointer to that value.
>
> Deletate literals
>
> * When a delegate literal *only* references variables inside a heap{}
> block, then its 'this' pointer should point to the heap, of course.
> * When a delegate literal accesses variables on the stack, then its
> 'this' pointer should point to the stack.
>
> Q: Should it be legal to have a delegate which accesses both heap and
> stack variables? Probably, but won't it sometimes make it non-obvious
> which thing the delegate points to?
>
> BTW: There is no reason that heap{} blocks couldn't be nested. There
> might be cases where the outer heap area might become garbage while the
> inner heap area does not.
Is a special syntax really desired for this sort of things. In other
languages there is something called static closures and if i understand
them right they are often implemented so that the returned function gets
a copy of its referred variables probably heap allocated.
The downside with this is that to modify a referred variable a pointer
is required but on the other hand it removes a chore from the programmer
and a source of mistakes. (if we wanted to we could declare a syntax to
override the copy part and instead pass a pointer. example follows)
int c=0;
void delegate() foo()
{
void a()
{
c++;//c is a copy and is unchanged after the return
}
return &a;
}
void bar()
{
int* f=&c;
void b()
{
++ at c;//c is implicitly accessed trough a pointer
++*f;//this line is equivalent
//f is a copy of a pointer but it points to the original
//c in the case of @c this is done by the compiler
}
return &b;
}
I don't know what's the better syntax but i feel that any syntax that
require the variables to bee declared with special storage is prone to
mistakes and bugs.
More information about the Digitalmars-d
mailing list