我对 C++ 相当了解。我在其他语言中使用过 lambda 和闭包。为了我的学习,我想看看在 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 = " << y << " at creation" << endl;
auto f = [&y](int toAdd) {
y += toAdd;
return y;
};
return f;
}
void test(const function<int (int)>& f, const int arg, const int expected) {
const int result = f(arg);
cout << "arg: " << arg
<< " expected: " << expected << " "
<< (expected == result ? "=" : "!") << "= "
<< "result: " << result << endl;
}
int main(int argc, char **argv) {
auto s = actsStatic();
test(s, 1, 1);
test(s, 1, 2);
test(actsStatic(), 1, 1);
test(s, 1, 3);
auto w = actsWicked();
test(w, 1, 1);
test(w, 1, 2);
test(actsWicked(), 1, 1);
test(w, 1, 3);
return 0;
}
结果:
arg: 1 expected: 1 == result: 1
arg: 1 expected: 2 == result: 2
arg: 1 expected: 1 != result: 3
arg: 1 expected: 3 != result: 4
actsWicked: y = 0 at creation
arg: 1 expected: 1 == result: 1
arg: 1 expected: 2 == result: 2
actsWicked: y = 0 at creation
arg: 1 expected: 1 == result: 1
arg: 1 expected: 3 != result: 153207395