Linus with some good observations on garbage collection

bearophile bearophileHUGS at lycos.com
Sat Apr 23 07:22:55 PDT 2011


Andrei:

> Well in fairness they can be a fair amount more elaborate. The trouble 
> with alloca is that it's impossible to compose with. So in general you 
> need to write something like:
> 
> bool onStack = smallEnough(length * sizeof(T));
> auto a = (cast(T*) (onStack ? alloca : malloc)(length * sizeof(T)));
> scope(exit) if (!onStack) free(a.ptr);
> initialize(enforce(a));
> scope(exit) clear(a);
> 
> This block is difficult to factor out because of alloca.

See this too:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=135208

Keep in mind that alloca() returns null more often than malloc, and when alloca() return null, it's still meaningful to try to use malloc(). So the semantics you have written is not good enough yet (as mine. A merge of the two seems better).

My idea of D-style VLAs is something built-in that encapsulates that semantics (that's more complex than C99 VLA semantics).

I am suggesting a built-in because there is some more semantics to keep into account for a good implementation:
- Probably you want the arrays created on the stack to have an immutable length (otherwise you have to switch to a normal fully GC-heap dynamic array, but I don't like this).
- You have to return such arrays from functions, and to give them to function arguments. As fixed-sized arrays they probably need to be managed by value (unless you use "ref"), so they are different from dynamic arrays, and closer to fixed-sized ones.

Bye,
bearophile


More information about the Digitalmars-d mailing list