我非常了解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) conv.h
class Base
{
public:
void foo();
};
class Derived: public Base
{
public:
void bar();
};
class A {};
class B
{
public:
void koko();
};
Run Code Online (Sandbox Code Playgroud)
conv.cpp
void Base::foo()
{
cout<<"stamm";
}
void Derived::bar()
{
cout<<"bar shoudn't work"<<endl;
}
void B::koko()
{
cout<<"koko shoudn't work"<<endl;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include "conv.h"
#include <iostream>
int main()
{
Base * a = new Base;
Derived * b = static_cast<Derived*>(a);
b->bar();
Derived * c = reinterpret_cast<Derived*>(a);
c->bar();
A* s1 = new A;
B* s2 …Run Code Online (Sandbox Code Playgroud)