> If you're using RAII consistently and correctly then the problems > associated with heap memory go away, so you don't need to avoid the > heap. If you're not using RAII correctly, your proposal won't work > anyway and you'll leak memory. So what's the point? > > Why is it better to do dynamic allocation on the stack? (Answer: it's not.) > > You say "A record of all allocated objects by this function has to be > kept. Also, there will be gaps or fragmentation in Stack because of > this for which we will have to move allocated area down almost in all > cases and sometimes up." You haven't got rid of heap, you've got rid > of the stack, making using the stack as complicated as using the heap. > How do you propose to move the area? You have to adjust all pointers > referring to it, which is not possible in the general case (even if > you scan the process' entire memory to look for pointer-like patterns, > they could be obfuscated or stored in a file, or outside the process > in other ways.) If the stack needs to grow to call a function, but > the space it wants to grow into contains dynamically-allocated > objects, what happens? Does the stack skip over that block, > remembering where to skip back over it when unwinding? Your stack is > no longer contiguous and must keep track of far more information. A > stack pointer won't work anymore. > > There are good reasons why dynamic memory, which has unpredictable > lifetime, is kept in a separate region from stack memory, which > doesn't. > > I agree the proposal is hopeless. >
To add more, I am trying to enforce RAII. You are not allowed to do memory allocation at any place other than construction and deallocate it other than destructor. Hope you get the point. -- Best regards, Shiv Shankar Dayal