Sunday 3 February 2013


About new keyword in C:

Allocates memory for the object on the free store (This is frequently the same thing as the heap ) Requires you to explicitly delete your object later. (If you don't delete it, you could createa memory leak) Memory stays allocated until you delete it. (i.e. you could return an object that you created using new )

The example in the question will leak memory unless the pointer is delete d; and it should always be deleted , regardless of which control path is taken, or if exceptionsare thrown.

Not using new:
Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.

You won't need to delete it later.

Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Object * obj = new Object ();
new always return pointer to object.
if you write just- 
Object obj; 

it means that obj will hold the object itself. If it is declared this way inside function then memory will be allocated on stack and will be wiped once you leave that function. new allocates memory on heap, so the pointer can be returned from function. Note that pointer canalso point to local (stack) variable also.

No comments:

Post a Comment