Archived

This topic is now archived and is closed to further replies.

Prime

Brain freeze and pointers from functions

Recommended Posts

Prime    122
Hi, This seems like a simple problem, and I feel quite silly for asking it, but I am wondering about manipulating pointers in functions. Allow me to be more specific. I have a function that I want to use to instantiate an object. When the object is created I want to return a pointer to that object, so it can be used outside this function. But since the object is local to the function, isn''t its destructor called when the function exits? Now, what does the returned pointer point to after the function exits? Is it garbage? So, I guess I''m wondering what is the best way to create objects locally in a function and then use them outside the function. Thanks for straightening out my murky mind... Prime

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Yes, if you return a pointer to a local object then that pointer is garbage. You must use new to create a new object in your case:

Foo * Create()
{
Foo * p = new Foo;

// initialize *p

return p;
}

Share this post


Link to post
Share on other sites
c_wraith    122
In case the AP''s post wasn''t clear enough for you:

Only objects allocated within the stack are automatically released when a function returns. So if you have something like:

  
Obj *foo()
{
Obj o=Obj(); // Ack. I''m not used to C++ syntax. Is this right?

return &o;
}


That won''t work, because the object is created locally, in the stack. However, this:

  
Obj *foo()
{
Obj *o = new Obj();
return o;
}


That will work, because the object is created in the heap. The pointer is all that is local, so it goes out of scope. However, the returned pointer is in scope in the calling function, and the data it refers to is still valid. The object still exists in the heap, and still needs to be deleted when it isn''t necessary anymore.

Share this post


Link to post
Share on other sites