no.*_*nod 1 c++ lambda closures decorator
我创建了decorator函数来向现有函数添加功能。该程序输出正确的函数指针地址以及helloworld按预期迭代 10 x所用的时间。
然而,如果我将decorator函数更改为采用original_functionby 值 ( FunctionPointer original_function),程序将因分段错误而终止,我不明白它失败的原因。
#include <iostream>
#include <chrono>
typedef void (*FunctionPointer)();
auto
decorator(FunctionPointer && original_function) // if changed to FunctionPointer original_function, it causes segmentation fault when the closure(lambda expression) is called later on
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90
return [&]()
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90 but 0x0 when original_function passed by value
auto t0 = std::chrono::high_resolution_clock::now();
original_function();
auto duration = std::chrono::high_resolution_clock::now() - t0;
std::cout << "\nElapsed " << duration.count() * 1000.0f << " ms\n";
};
}
void
helloworld(void)
{
for (auto i = 0; i < 10; i++)
std::cout << "Hello, World!\n";
}
int
main(void)
{
std::cout << "Main: " << (void*)helloworld << std::endl; // 0x558072fb0b90
auto my_helloworld = decorator(helloworld);
my_helloworld();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不同之处在于,当您按值传递函数时,传入 lambda 的参数是对函数 parameter的引用,它在decorator返回时超出范围。当您稍后调用返回的 lambda 时,您引用了这个超出范围的变量,即未定义行为。
当您通过通用引用传递时,它起作用,传递给的参数decorator是一个引用,该引用传递给 lambda。所以当你调用 lambda 时它仍然有效。
您可以将 lambda 更改为按值传递(使用[=])以使更改后的版本正常工作。