Brain freeze and pointers from functions

Started by
2 comments, last by Prime 22 years, 8 months ago
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
Advertisement
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;
}

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.
Thanks a lot. Now it is once again all clear to me.

Prime

This topic is closed to new replies.

Advertisement