返回局部变量 [英] returning local variables

查看:150
本文介绍了返回局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到了一个关于局部变量的问题。我学到了...

I came across an issue today regarding local variables. I learned that...

 int * somefunc()
 {
     int x = 5;
     return &x;
 }

 int * y = somefunc();
 //do something

是不好的,不安全的等等。我想象, case是相同的...

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;

我一直在印象最长的时间,这将是安全的,因为地址x保留在范围内,当它返回。然而,我现在有第二个想法,我认为这将导致内存泄漏和其他问题,就像第一个例子。有人可以为我确认这个吗?

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:

int * somefunc()
{
    int * x = new int;
    *x = 5; // note the dereferencing of x here
    return x;
}

现在这在技术上很好,但它容易出错。首先,如果在分配 x 后发生异常,您必须捕获它,删除 x 然后重新抛出,或者你得到一个内存泄漏。第二,如果你返回一个指针,调用者必须删除它 - 调用者忘记。

Now this is technically fine, but it is prone to errors. First, if after the allocation of x an exception happens, you have to catch it, delete x and then rethrow, or you get a memory-leak. Second, if you return a pointer, the caller has to delete it - callers forget.

建议的方法是返回一个智能指针,如 boost :: shared_ptr 。这将解决上述问题。要了解原因,请参阅 RAII

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.

这篇关于返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆