返回地址到局部变量与返回指针到局部变量 [英] Returning an address to a local variable vs returning a pointer to a local variable

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

问题描述

我在我的testing.cpp中有这个

I have this in my testing.cpp:

class Supp{
public:
virtual Supp* add(Supp& val) = 0;
};

class SubA : public Supp{
public:
int val;

SubA(int a){
    val = a;
}
int getVal(){
    return val;
}
Supp* add(Supp& value){
    SubA& a = dynamic_cast<SubA&>(value);
    int tempVal = a.getVal();
    int sum = val + tempVal;
    SubA b =SubA(sum);
    return &b;
}
};

和行

SubA b = SubA(sum); return &b;

SubA b = SubA(sum); return &b;

给与错误,因为它将地址返回到一个非常难做的局部变量,所以我将其更改为

gives and error because itreturns the address to a local variable which is very bad to do, so i changed it to

SubA* b =new SubA(sum); return b;

SubA* b =new SubA(sum); return b;

,并且可以正常工作且没有错误,但是,这基本上不是一回事吗?为什么这对编译器合法,但以前的版本不合法?

and it works fine with no errors, But is this not basically the same thing? why is this legal to the compiler but the previous version not?

推荐答案

将地址返回给局部变量是非法的,原因是一旦函数返回,该局部变量就不复存在了,因此您返回的地址是已知不再有效. (该对象可能仍然存在,但是其析构函数将已经被调用,并且它所占用的内存将在某些时候用于其他用途-也许与下一个子例程调用一样.)

The reason it's illegal to return the address to a local variable is once the function returns, the local variable ceases to exist, thus you're returning an address which is known to be no longer valid. (The object may still live there but its destructor will have already been called, and the memory it occupied will be used for something else at some point -- perhaps with the very next subroutine call.)

可以返回new返回的地址是可以的,原因是该地址未指向驻留在临时位置的对象(您的程序堆栈通常是本地人所在的位置);而是来自堆内存,该内存将一直持续到您处理掉为止.该对象不依赖于分配该对象的代码范围,因为它不在该范围内.

The reason it's ok to return the address returned by new is that address is not pointing to an object that lives in a temporary location (your program stack is where locals are normally placed); rather it comes from heap memory which will persist until you dispose of it. This object doesn't rely on the scope of code it was allocated in since it's not local to that scope.

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

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