为什么lambda捕获的这个指针被破坏而其他变量没有

时间:2014-07-25 17:42:34

标签: c++ pointers c++11 lambda

我编译了(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]会导致该内容损坏。

2 个答案:

答案 0 :(得分:6)

未定义的行为,无疑。你刚刚销毁了你正在执行的lambda。

答案 1 :(得分:1)

您正在呼叫delete this->a;,而this->a正在召唤f,导致UB。