I know this won\'T work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4; return &x;
}
<
C++ approach to avoid memory leaks. (at least when You ignore function output)
std::auto_ptr myFunction() {
std::auto_ptr result(new int(4));
return result;
}
Then call it:
std::auto_ptr myFunctionResult = myFunction();
EDIT: As pointed out by Joel. std::auto_ptr has it's own drawbacks and generally should be avoided. Instead std::auto_ptr You could use boost::shared_ptr (std::tr1::shared_ptr).
boost::shared_ptr myFunction() {
boost::shared_ptr result(new int(5));
return result;
}
or when use C++0x conforming compiler You can use std::unique_ptr.
std::tr1::unique_ptr myFunction() {
std::tr1::unique_ptr result(new int(5));
return result;
}
The main difference is that:
shared_ptr allows multiple instances of shared_ptr pointing to the same RAW pointer. It uses reference counting mechanism to ensure that memory will not be freed as long as at least one instance of shared_ptr exist.
unique_ptr allows only one instance of it holding pointer but have true move semantic unlike auto_ptr.