gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:36 25 4
gpt4 key购买 nike

我已编译 (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

我不明白为什么 captures this 改变了它的值,而不同名称的相同指针却没有损坏。

编辑:

我知道 lambda 已被破坏并且我正在生成 UB 但我不明白的是为什么一个变量被破坏而另一个没有。我不理解这种行为背后的底层细节,顺便说一下,这是非常一致的。我想了解导致这种行为的 gcc 实现细节。

我的进一步调查表明,将 auto f = [this, that] 更改为 auto f = [that, this] 会导致 that 损坏。

最佳答案

未定义的行为,innit。您刚刚销毁了正在执行的 lambda。

关于c++ - 为什么 lambda 捕获的这个指针被破坏而其他变量没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com