Re: questions about pointers in container
On Aug 3, 4:38 pm, trade...@yahoo.com wrote:
If my purpose is initialize data from xml files and store them in the
vector, so they can be used in class B by other member functions, do
you think functionP is a viable function(will a could go away after
out of the function)?
void functionP(){
...
A a;
v.push_back(a);
}
That would work. Yes, 'a' would be terminated at the end of functionP.
Since 'v' would be containing a *copy* of 'a' you are good.
If not, is there a better solution than using functionPt?
void functionPt(){
...
A* aPt ;
vPt.push_back(aPt);
}
You would need a vector of pointers if the objects that you create a
polymorphic. Otherwise go with functionP.
I read that it is not a good design to have container for pointers(C++
FAQs), but I cannot see how I can get around it in my situation.
If you have polymorphic objects, store them either as smart pointers
in a vector, or use a "pointer vector" that knowns to delete the
objects when itself is going away.
Using the Boost library's reference counted pointer:
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<A> APtr;
typedef vector<APtr> APointers;
APointers my_a_collection;
my_a_collection.push_back(APtr(new SomeDecendentOfA()));
See the Boost library for their pointer vector.
Ali