Tuesday, 12 December 2017

c++ - Which is better: storing objects vs storing pointers?

I want to store elements (let's call it E), but I don't
know that I should store them as objects or as pointers pointing to the dynamically
allocated objects.



(A,B,C,etc. objects
store the reference of the wanted
E)




version
A:



E
e;
store.Add(e); //This time the store contains
objects.


In this
version the element will be copied to the store, but it's easier to handle. (The objects
will be destroyed when the parent object is
destroyed)



version
B:




E* e
= new E();
store.Add(*e); //This time the store contains
references.
/*I chose references instead of pointers,
so I have to
use pointers only at allocating and
deallocating.*/


In
this version there is no copy constr. but I have to delete the objects in the parent
object's destructor.



Which is better and why?
Which can cause more mistakes and which is more efficient?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...