Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer allocation vs normal declaration

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
like image 750
Anthony Avatar asked Dec 23 '22 05:12

Anthony


2 Answers

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.

like image 198
sharptooth Avatar answered Dec 24 '22 18:12

sharptooth


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).

like image 33
digitalarbeiter Avatar answered Dec 24 '22 18:12

digitalarbeiter