gpt4 book ai didi

c++ - 递归 lambda 和捕获(段错误)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:58 24 4
gpt4 key购买 nike

编译器

g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010

片段 1(& 捕获)

#include <functional>

int main()
{
std::function<void ()> func = [&] () {
func();
};
return 0;
}

片段 2(func 捕获)

#include <functional>

int main()
{
std::function<void ()> func = [func] () {
func();
};
return 0;
}

两个片段都能编译,但为什么运行第二个片段会导致段错误?

最佳答案

捕获发生在构建 std::function 之前.

因此,您捕获了 std::function<void()> func 的未初始化(甚至不是默认构造的!)拷贝.所有这一切本身就是对 std::function 的捕获是 UB(在构造变量之前复制变量!),调用它甚至会“更加 UB”(调用非构造 std::function 的拷贝!)。

引用案例捕获了对 func 的引用,即使在初始化之前也是允许的,只要它只在初始化后使用。

引用案例的缺点是 lambda 仅在 func 范围内有效.复制一次也是无效的func超出范围。根据我的经验,这很糟糕。

要执行真正的“全强度”递归 lambda,您需要类似 y 组合器的东西。

这是一个简短的 C++14 y 组合器:

template<class F>
auto y_combinate( F&& f ) {
return [f = std::forward<F>(f)](auto&&...args) {
return f(f, decltype(args)(args)...);
};
}

你传递给它一个 lambda,它期望将对自身的引用作为第一个参数:

std::function<void ()> func = y_combinate( [](auto&& self) {
self(self);
}
);

剩下的就交给它了。

y 组合器要求是因为您无权访问自己的 this在 lambda 的体内。所以我们加一个。

上面的 y-combinator 只有 90%,因为它没有完美地处理传入的函数对象的 r/l 值和 const-ness。但它会在大部分时间提供服务。

这是一个稍微好一点的 y 组合:

template<class F>
struct y_combinate_t {
F f;
template<class...Args>
decltype(auto) operator()(Args&&...args)const {
return f(*this, std::forward<Args>(args)...);
}
};
template<class F>
y_combinate_t<std::decay_t<F>> y_combinate( F&& f ) {
return {std::forward<F>(f)};
}

这样使用起来更好:

std::function<void ()> func = y_combinate( [](auto&& self) {
self();
}
);

self现在传进去就不用传了self调用时本身。

关于c++ - 递归 lambda 和捕获(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021455/

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