将地址返回到局部变量与返回指向局部变量的指针
我的 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);返回 &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);返回 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.
相关文章