Re: Always avoid "new"

From: Niels Dybdahl (ndy_at_fjern.detteesko-graphics.com)
Date: 04/30/04


Date: Fri, 30 Apr 2004 11:26:34 +0200


> Is it right thing to always avoid using "new" to create objects? What if
> after starting the application, then decide which and how many objects to
> create? (Seems like under such situation is there no other choice but
using
> "new")

I do actually avoid "new" as much as possible. The reason is this: The
destructor and deallocator are not called automatically, so to prevent
memory leaks other methods are needed such as try, catch or destructors from
other objects.

Of course if I need a variable number of objects, then I use new and store
the objects in a vector and let the vector do the cleanup. Or in those cases
where I do not store the object(s) in a vector, I store them in some other
object and make that objects destructor ensure cleanup.

An additional advantage of allocating on the stack instead of the heap, is
that if you have tested your application and thereby verified that there is
enough space on the stack, then you can be sure that there will always be
enough space on the stack for your objects (unless you depend on recursion).
With the heap you can not be sure that there is enough space and you risk
exceptions on that account.

Niels Dybdahl



Relevant Pages

  • Re: newbee - heap and stack
    ... "The heap and the stack are the two places where programs store data (okay, ... The heap is just a big chunk of memory that is managed by a heap manager (or ... Employee e = new Employee; ... The stack is used to hold local variables. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: stack and a heap
    ... >> They are both memory which is used to store objects. ... The stack is also used to ... > can end up on the heap as part of other objects. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: alloca / _alloca / dynamic stack memory
    ... to know the difference between allocating on the stack from ... allocating on the heap. ... time...perhaps it has a private/protected destructor, ...
    (microsoft.public.vc.language)
  • Re: Single Class vs Multiple Class
    ... session...does it store all the methods and functions too? ... In the heap (or on the stack - for ValueType variables) only "data" is stored, so adding methods does not alter the amount of heap used. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: [PATCH -v5 10/11] tracing: add function graph tracer support for MIPS
    ... Probably want to put the above in an asm with exception handling. ... Yes with -mlong-calls you must jump pass the setting up of the jalr. ... "Store" instruction, the function should be a leaf? ... instruction, get the offset, calculate the stack address, and finish? ...
    (Linux-Kernel)

Loading