I am coming from a C# background to C++. Say I have a method that creates a object in a method on the stack, then I pass it to another classes method which adds it to a memeber vector.
void DoStuff()
{
SimpleObj so = SimpleObj("Data", 4);
memobj.Add(so);
}
//In memobj
void Add(SimpleObj& so)
{
memVec.push_back(so); //boost::ptr_vector object
}
Here are my questions:
I realise these are probably obvious to a C++ programmer with some expereince.
Mark
The simplest way to achieve what you are trying to do would be to store a copy of the objects in a normal STL container (e.g. std::vector
). If such objects are heavyweight and costly to copy around, you may want to allocate them on the heap store them in a container of adequate smart pointers, e.g. boost::shared_ptr
(see the example in @Space_C0wb0y's answer).
Another possibility is to use the boost::ptr_vector
in association with boost::ptr_vector_owner
; this last class takes care of "owning" the objects stored in the associated ptr_vector
, and deleting all the pointers when it goes out of scope. For more information on ptr_vector
and ptr_vector_owner
, you may want to have a look at this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With