如果方法中的变量是临时的。那为什么我们可以访问它们 C++?

If variables within a method are temporary. Then why can we access them C++?

您好;
我有一个关于我面临的小问题的问题。
如果函数中的变量是临时的。例如:

int* simpleCopy(int *newvalue)
{
   int result;
   int* pointerToResult;
   result = *newvalue;
   pointerToResult = &result;
   return pointerToResult;
}

如果我们尝试使用此功能,它将起作用。但是我不明白为什么。


从编译器的角度来看:

the function will create a variable named result and a pointer that point to this variable. and then will return the pointer. But when the function finishes and return the pointer the variable should be already gone yet It works and gives me accurate result. Could anyone explain the reason to me please.
Thanks in previos

Could anyone explain the reason to me please.

从语言的角度来看:如果您试图在对象的生命周期之外访问该对象,则程序的行为是未定义的。

一个假设的编译器的观点:你通过指针间接。编译器一般不知道它指向哪里。它只是生成指令来读取值。那段内存可能包含也可能不包含与那里有对象时它所做的相同的位。内存可能已用于其他用途,也可能没有。也许内存包含一些特殊的陷阱表示,导致 CPU 中断并发出信号。

这是 UB 这一事实是正确的回应。人们会为此进行激烈的斗争。甚至说除了"it's UB"

你不许说别的

但这不是一个很有用的答案。它 'wotks' 的原因是您的实现使用了堆栈。当您调入 simpleCopy 时,它会推送一些额外的内存,包括 space 用于 result。当你返回时,堆栈被弹出,但内存保持不变。

由于您没有调用其他函数(事实上,直到您调用),结果仍然存在。但是你绝对不应该依赖这个。

原因是优化编译器执行了大量的代码修改。他们这样做是假设您不会尝试访问超出范围的变量。