我有以下代码.
#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
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
我非常了解C++.我在其他语言中使用过lambdas和closures.为了我的学习,我想看看我能用C++做些什么.
完全知道"危险"并期望编译器拒绝这一点,我通过引用使用函数堆栈变量在函数中创建了一个lambda并返回了lambda.编译器允许它并且发生了奇怪的事情.
为什么编译器允许这样做?这只是编译器无法检测到我做了非常非常糟糕的事情并且结果只是"未定义的行为"的问题吗?这是编译器问题吗?该规范有什么可说的吗?
在最近的Mac上测试,使用MacPorts安装的gcc 4.7.1和-std = c ++ 11编译选项.
使用的代码:
#include <functional>
#include <iostream>
using namespace std;
// This is the same as actsWicked() except for the commented out line
function<int (int)> actsStatic() {
int y = 0;
// cout << "y = " << y << " at creation" << endl;
auto f = [&y](int toAdd) {
y += toAdd;
return y;
};
return f;
}
function<int (int)> actsWicked() {
int y = 0;
cout << "actsWicked: y = …Run Code Online (Sandbox Code Playgroud)