I know this won\'T work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4; return &x;
}
<
Boost or TR1 shared pointers are generally the way to go. It avoids the copy overhead, and gives you semi-automatic deletion. So your function should look like:
boost::shared_ptr myFunction2()
{
boost::shared_ptr x = new int;
*x = 4;
return x;
}
The other option is just to allow a copy. That's not too bad if the object is small (like this one) or you can arrange to create the object in the return statement. The compiler will usually optimize a copy away if the object is created in the return statement.