views:

134

answers:

6

Hi, sometimes I see in various C++ programs, objects declared and used like so:

object *obj = new object;
obj->action();
obj->moreAction();
//etc...

Is there any benefit of doing that, instead of simply doing:

object obj;
obj.action();
obj.moreAction();
//etc
+5  A: 

Yes - you can store the pointer in a container or return it from the function and the object will not get destroyed when the pointer goes out of scope. Pointers are used

  • to avoid unnecessary copying of object,
  • to facilitate optional object creation,
  • for custom object lifetime management,
  • for creating complex graph-like structures,
  • for the combinations of the above.

This doesn't come for free - you need to destroy the object manually (delete) when you no longer need it and deciding when this moment comes is not always easy, plus you might just forget to code it.

sharptooth
+1  A: 

Basically, you should only use "new" if you want an object to live beyond the lifetime of the scope you create it in. For eg:

X* g(int i) { /* ... */ return new X(i); } // the X outlives the call of g()

If you want an object to live in a scope only, don't use "new" but simply define a variable:

{
    ClassName x;
    // use x
}
Jagannath
A: 

It comes down to having more control over the lifecycle of the object in question (when using new).

jldupont
+3  A: 

The first form, allocating objects on the heap, gives you full control of (and full responsibility for) the object's live time: you have to delete obj explicitly.

In the second form, the object is automatically and irrevocably destroyed when obj goes out of score (when leaving the current code block).

digitalarbeiter
You almost mentioned it but it can be worth pointing out that the second frame is created on the stack.
Patrick
+2  A: 

One other reason no-one has mentioned.
The stack is typically 1Mb, so creating large objects must be done on the heap ( with new)

Martin Beckett
8 MB on my vanilla Ubuntu 9.04 (which actually _proves_ your point rather than contradicting it)
digitalarbeiter
A: 

Yes there is a good reason: you have much more chance to have a correct program when using the latter form..

The problem is that the former form (pointer) is a Cism, in C++ you should use a smart pointer to ensure proper destruction of the object at the end of its life.

Now, if you use std::auto_ptr<Object> obj(new Object()); you have 3 benefits:

  1. you now manage the life cycle of your object explicitly (but cannot forget it)
  2. you can store you object into a container with polymorphism
  3. you do not clog the stack, and thus have less risk of running into a stack overflow
Matthieu M.