【发布时间】:2014-09-17 15:38:28
【问题描述】:
我已编译 (g++ -std=c++11 a.cpp) 并运行以下代码:
#include <iostream>
#include <functional>
using namespace std;
class A {
std::function<void(void)> f;
public:
A(std::function<void(void)> pf) : f(pf) {}
void callf() { f(); }
};
class B {
A *a;
public:
void test() {
B *that = this;
auto f = [this, that]() {
cout << "this: " << this << " that: " << that << endl;
delete this->a;
cout << "this: " << this << " that: " << that << endl;
};
a = new A(f);
a->callf();
}
};
int main()
{
B().test();
}
它的输出是:
this: 0x7fff158c88f0 that: 0x7fff158c88f0
this: 0x1ea3000 that: 0x7fff158c88f0
我不明白为什么捕获的这个改变了它的值,而具有不同名称的相同指针没有损坏。
编辑:
我知道 lambda 已被破坏并且我正在生成 UB,但我不明白为什么一个变量已损坏而其他变量未损坏。我不了解这种行为背后的低级细节,顺便说一句,这是非常一致的。我想了解导致这种行为的 gcc 实现细节。
我的进一步调查表明,将 auto f = [this, that] 更改为 auto f = [that, this] 会导致其损坏。
【问题讨论】: