On 10/8/2011 6:05 AM, Jonathan Wakely wrote:
> 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.)
...
> There are good reasons why dynamic memory, which has unpredictable
> lifetime, is kept in a separate region from stack memory, which
> doesn't.

The reason many real-time systems disallow use of the heap is because it
is well-known that heap management does not have a bounded-time
implementation.  Usually during free()/delete, typical heap management
code often tries to coalesce freed blocks, or perform various other
book-keeping. The length of time this takes is dependent on the usage
pattern of the process.  There are approaches to minimize the
'unboundedness' but that's like attempting to be "a little bit pregnant".

OTOH, presuming you have enough stack space, and all dynamic allocations
are scope-bounded, both allocation and freeing can be performed in
bounded (constant?) time.  This is relatively straightforward to do in
C, but C++ is much more difficult, especially if you use any Standard
Library facilities -- you have to write special allocators, and use them
consistently whenever instantiating any Standard Library type, and even
then it doesn't *guarantee* that you'll avoid the "regular" new operator
somewhere under the hood (say, an extern "C" call to canonicalize_path
or something).

> I agree the proposal is hopeless.

Not hopeless; but you have to treat C++ simply as a slightly more
expressive version of C, follow the same rules previously outlined just
as if you WERE using C, and avoid the STL...

At that point, are you REALLY using "C++" -- or should you simply call
it "C+"? <g>

Such a beast would be a separate dialect, which probably could be
implemented via a plugin.  But to avoid the hassle of checking whether
EVERY allocation avoided traditional heap-based new, the dialect would
likely need separate runtime library, where new/new[] (and malloc?) were
implemented in terms of stack allocation.  Doing THAT would violate some
(many?) of the behavioral requirements of the C++ standard, so...

--
Chuck

Reply via email to