11/4/2012 9:35 PM, Tommi пишет:
I have a fundamental language design talking point for you. It's not
specific to D. I claim that, most of the time, a programmer cannot, and
shouldn't have to, make the decision of whether to allocate on stack or
heap.

Actually it can and most definitely should. It's scoped lifetime vs infinite lifetime, reference and value semantics. And e.g. RAII structs have to be on stack to have their effect applied usefully. Storing the reference to 't' elsewhere implies heap allocation (be it GC heap or manually managed one).

Going further allocation strategy is a deep topic with a lot of considerations and in the end it goes far beyond stack vs GC heap.

For example:

void func(T)()
{
     auto t = <allocate T from heap or stack?>
     ...
}

The question of whether variable t should lay in heap or stack, depends
not only on the sizeof(T), but also on the context in which func is
called at. If func is called at a context in which allocating T on stack
would cause a stack overflow, then t should be allocated from the heap.

In fact placing big object on stack just because it fits could introduce stack overflow few hundred calls later. In general compiler can't know beforehand how big stack space you'll need and thusly the portion of it to use safely.

On the other hand, if func is called at a context where T still fits
nicely on the stack, it would probably be better and faster to allocate
t on stack.

Unless you escape references. Compiler could detect it but will stay on the conservative side. In the end it may end up with unexpected heap allocations.


So, the question of whether to allocate that variable t on stack or heap
is something that only the compiler (or runtime) can answer.

God no. It may as well depend on the code compiler knows nothing about (nor run-time for this matter).

extern(C):
int blah(void* ptr);

void func(T)()
{
      auto t = <allocate T from heap or stack?>
      blah(&t); //now what?
      ...
}

If blah doesn't store pointer somewhere inside you are fine with stack. If it does then not even GC heap will help you.

Is there
any language where you have the ability to say "allocate T from wherever
it's best"?

In simplest case I'd consider ability to bypass allocation on heap as an optimization.

I wonder if it would be possible in D to let the compiler allocate
dynamic arrays on stack when it can statically guarantee that it's safe
to do so (no dangling references, never increasing the size of the
array, etc).


--
Dmitry Olshansky

Reply via email to