I came across an issue today regarding local variables. I learned that…
int * somefunc()
{
int x = 5;
return &x;
}
int * y = somefunc();
//do something
is bad, unsafe, etc. I’d imagine that the case is the same for…
int * somefunc()
{
int * x = new int;
x = 5;
return x;
}
int * y = somefunc();
//do something
delete y;
I’ve been under the impression for the longest time that this would be safe as the address of x stays in scope when it’s returned. However, I’m having second thoughts now and I’m thinking this would lead to memory leaks and other problems, just as the fist example would. Can someone confirm this for me?
As it stands, the second example is wrong. You probably meant this:
Now this is technically fine, but it is prone to errors. First, if after the allocation of
xan exception happens, you have to catch it, deletexand then rethrow, or you get a memory-leak. Second, if you return a pointer, the caller has to delete it – callers forget.The recommended way would be to return a smart pointer, like
boost::shared_ptr. This would solve the problems mentioned above. To understand why, read about RAII.