Brain freeze and pointers from functions
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
PRIMEWarped Productions
August 06, 2001 01:19 PM
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;
}
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:
That won''t work, because the object is created locally, in the stack. However, this:
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.
Only objects allocated within the stack are automatically released when a function returns. So if you have something like:
|
That won''t work, because the object is created locally, in the stack. However, this:
|
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
Prime
PRIMEWarped Productions
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement