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:
- Once the DoStuff methods ends will the so go out of scope and be popped from the stack?
- memVec has a pointer to so but it got popped what happens here?
- Whats the correct way to pass stack objects to methods that will store them as pointers?
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_vectorin association withboost::ptr_vector_owner; this last class takes care of “owning” the objects stored in the associatedptr_vector, and deleting all the pointers when it goes out of scope. For more information onptr_vectorandptr_vector_owner, you may want to have a look at this article.