I’m tring to learn C++ and I have a little problem. I have some instances of Foo class. And I have a FooContainer with vector<Foo> data with a method
void FooContainer::add(Foo item) {
this->data.push_back(item)
}
I want FooContainer to be the real holder of Foo elements. I don’t understand what is the better way to pass the items from main to Foo.
In my main I have:
Foo item(...);
container.add(item);
In this way I have an object allocated in main, and I pass a copy to the container. I have the element existing in 2 place, so I have to delete the one in the main after all add().
Or is better to have a pointer in the main, construct the item with new keyword, and pass the pointer? And in this way Container.data should be a vector<Foo*>?
Or, again, have the element in main, add in the container by reference, and not delete it in main?
I’m a bit confused.
EDIT
for educational purpose i don’t want to use c++11 or boost shared pointer: my ideas are confused on pointer and reference and basic things, before pass into advanced argument (even if more elegant) i want to have clear basis of what i am doing!
It all depends on your need.
If all your instances are
Foo[and not a subclass ofFoo], IMO usingvector<Foo>is simpler and thus should be preferred.However, if you have a class
Barwhich extendsFoo, trying to add it to yourvectorwill cause object slicing, and your program will behave not as expected. In this case, you should prefervector<Foo*>So, as I started – it all depends on the specific need, but the last point must be considered if you plan on extending
Foo.