我有以下代码.
#include <iostream>
int * foo()
{
int a = 5;
return &a;
}
int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)
而代码只是运行而没有运行时异常!
输出是 58
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
考虑一下:
std::string foo();
void bar() {
const std::string& r1 = foo();
static const std::string& r2 = foo();
}
Run Code Online (Sandbox Code Playgroud)
我知道第一次调用产生的字符串的生命周期foo()将延长到生命周期r1.
r2然而,暂时的约束呢?它会一直存在到示波器的末端,还是在bar()重新进入时仍然存在?
注意:我对特定编译器是否这样做感兴趣.(我对我们使用的那个很感兴趣,我可以轻松地测试它.)我想知道标准对此有何看法.