C++ Memory management by returning a pointer to a simple type
i want to ask about the following situ开发者_运维技巧ation
int * foo() {
int fooint = 5;
return &fooint;
}
int myint = *foo();
its based on http://www.functionx.com/cpp/examples/returnpointer.htm
but i want to ask, if it is safe, because what i think will happen
- fooint gets initialized in the scope of foo()
- the address of fooint is returned and foo() ends
- all variables in foo() gets destroyed
- so myint will hold the value, of an int at destroyed adress
wouldn't it be better to do
int * foo() {
int * fooint = new int;
*fooint = 5;
return fount;
}
int * tmp = foo();
int myint = * tmp;
delete tmp;
Yes, you shouldn't ever return addresses of temporary variables exactly for the reasons you give. The second variant is okay.
However using dynamic memory allocation for built-in types will be very expensive. In case of built-in types it'll much cheaper to just return by value:
int function()
{
return 5;
}
and it will also be less error-prone (no possibility for a memory leak for example).
Your analysis is spot on. I would strongly encourage you to stop reading that document.
Instead, please take a look at https://stackoverflow.com/questions/909323/what-are-good-online-resources-or-tutorials-to-learn-c
The question is why do you want to return a pointer? The normal thing to do is to return a value:
int foo() {
int fooint = 5;
return fooint;
}
In general, you should avoid dynamic memory allocation with new wherever possible and instead let the compiler manage things for you.
You're right, you should not return addresses of temporary variables, and neither should you new something in a function and then return it, expecting the caller to clean it up (unless, of course, it is wrapped in something such as boost::shared_ptr
).
So, for non-POD types, your class will need to have a copy constructor for the temporary (and perhaps a move constructor if you're using C++0x for better performance).
This will cause a common problem called dangling pointer.
When you do not have memory management system such as Garbage Collection (or smart pointers) you should always ask count the references and use the delete
instruction in proper locations at the right times, a general rule of thumb is to never share the address of stack variables in different scopes.
精彩评论