Returning an address to a local variable vs returning a pointer to a local variable(将地址返回到局部变量与返回指向局部变量的指针)
问题描述
我的 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.
这篇关于将地址返回到局部变量与返回指向局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将地址返回到局部变量与返回指向局部变量的指针
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01