returning local variables

2019-02-20 13:25发布

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?

8条回答
三岁会撩人
2楼-- · 2019-02-20 13:59

Yes, you're taking the risk of leaking memory. (compile errors aside.) Doing this for an int is silly, but the principle is the same even if it's a large structure.

But understand: you've written C-style code, where you have a function that allocates storage.

If you're trying to learn C++, you should put somefunc() and the data it operates on into a class. Methods and data together. A class can also do RAII as Space_C0wb0y pointed out.

查看更多
Rolldiameter
3楼-- · 2019-02-20 14:01

(Edited)

Yes, the second is fine, so long as you dereference that 'x' before assigning!

查看更多
登录 后发表回答