A few times in my project, i have wanted to store objects in a list (Qt's QList in this case, but it could be std::vector or any collection object) where i am storing the actual object and not a pointer to an object created on the heap. In other words:
//This:
List<Object> something;
//Instead of this:
List<Object*> something;
Now, in the past i have usually stored pointers to objects because the objects themselves are owned by another object, and the list is used to keep track of all these objects.
So when i wanted to add an object to the list then call some methods on that object i would do:
List<Object*> theList;
...
Object* obj = new Object();
theList.add(obj);
obj->initializeOrSomething();
giveObjectToSomething(obj); // Note: this function takes a pointer
But i have realised that in a lot of cases you want the list to contain the actual objects as that list is responsible for adding/removing/maintaining those objects.
So when i want to do the above, i am not sure what the best way is:
List<Object> theList
...
theList.add(Object());
theList.last().initializeOrSomething();
giveObjectToSomething(&theList.last());
In other words, i don't know an easy way to obtain a reference to the object which i have just created.
I was thinking i could create it and add it like this:
List<Object> theList
...
Object obj;
theList.add(obj);
obj.initializeOrSomething();
giveObjectToSomething(&obj);
But wouldn't that copy the object?