Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object on the stack then passing by reference to another method in C++

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:

  1. Once the DoStuff methods ends will the so go out of scope and be popped from the stack?
  2. memVec has a pointer to so but it got popped what happens here?
  3. 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

like image 536
Mark Avatar asked Sep 21 '10 09:09

Mark


1 Answers

  1. Yes.
  2. The pointer remains "alive", but points to a no-longer-existent object. This means that the first time you try to dereference such pointer you'll go in undefined behavior (likely your program will crash, or, worse, will continue to run giving "strange" results).
  3. You simply don't do that if you want to keep them after the function returned. That's why heap allocation and containers which store copies of objects are used.

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.

like image 179
Matteo Italia Avatar answered Oct 13 '22 14:10

Matteo Italia