将lambda传递给超出范围的函数是否安全(lambda在方法返回后执行)? 我正在学习C++,所以我的问题可能是愚蠢的。我正在创建一个以lambda为参数的函数。我只是想知道当lambda函数超出范围时调用它是否安全。使用代码更容易解释我的意思: 结构SomeStruct { //指向回调函数的存储指针 无效(*回拨)(bool); int arg1; int-arg2; }; void some_方法(int arg1、int arg2、void(*on_complete_回调)(bool)) { 某些结构; s、 callback=在完成回调时; s、 arg1=arg1; s、 arg2=arg2; //此帮助器类将复制结构,即使它是通过引用传递的 SomeHelperClass->SomeQueue.enqueue(&s); //在单独的任务/线程上工作 SomeHelperClass->CreateThread([])(){ //获取结构的副本 SomeStruct s_copy; SomeHelperClass->SomeQueue.dequeue(&s\u copy); //做需要时间才能完成的工作 //调用这个回调函数安全吗? s_copy.callback(true); }); }
那么我的问题是,如果这样做安全吗?将lambda传递给超出范围的函数是否安全(lambda在方法返回后执行)? 我正在学习C++,所以我的问题可能是愚蠢的。我正在创建一个以lambda为参数的函数。我只是想知道当lambda函数超出范围时调用它是否安全。使用代码更容易解释我的意思: 结构SomeStruct { //指向回调函数的存储指针 无效(*回拨)(bool); int arg1; int-arg2; }; void some_方法(int arg1、int arg2、void(*on_complete_回调)(bool)) { 某些结构; s、 callback=在完成回调时; s、 arg1=arg1; s、 arg2=arg2; //此帮助器类将复制结构,即使它是通过引用传递的 SomeHelperClass->SomeQueue.enqueue(&s); //在单独的任务/线程上工作 SomeHelperClass->CreateThread([])(){ //获取结构的副本 SomeStruct s_copy; SomeHelperClass->SomeQueue.dequeue(&s\u copy); //做需要时间才能完成的工作 //调用这个回调函数安全吗? s_copy.callback(true); }); },c++,multithreading,C++,Multithreading,那么我的问题是,如果这样做安全吗? void method_1() { void (*foo)(bool) = [](bool completedCorrectly) { cout << "task completed :" << completedCorrectly << endl; }; some_method(1,2,foo); // at this point foo sh
void method_1()
{
void (*foo)(bool) = [](bool completedCorrectly)
{
cout << "task completed :" << completedCorrectly << endl;
};
some_method(1,2,foo);
// at this point foo should be deleted no?
// why does this work if foo is executed after method_1 completes and its stack is deleted?
// can I have code like that?
}
void方法_1()
{
无效(*foo)(bool)=[](bool正确完成)
{
coutlambda表达式类似于类。它是实例化对象的蓝图。类仅存在于源代码中。程序实际上使用由类定义的蓝图创建的对象。lambda表达式是创建闭包的源代码蓝图。每个lambda表达式都由编译器转换为类d实例化为一个名为closure的对象。该类能够捕获值(即[]
部分所做的),并为其调用运算符获取参数(即()
部分所做的)
以下是一个例子:
intmain()
{
int i=42;
auto l=[i](int const x){std::cout您的函数采用函数指针,而不是lambda。您是正确的@n.“代词m..我可能应该用函数指针重命名它。如果采用lambda,则有一种机制确保所有依赖对象都包含在该“包”中。这就是[]
定义用于。函数不存在于堆栈上,即使指向它的函数指针是从lambda获得的。那么这样编码安全吗?如果我每次使用不同的lambda多次调用该方法,它会一直工作吗?
#include <iostream> //for using cout
using namespace std; //for using cout
// 3 pointers
int* _X; // points to integer
int* _Y; // points to integer
void (*_F)(int); // points to function
void print_values()
{
cout << "x=" << *_X << " and y=" << *_Y << endl;
}
void some_function()
{
// create variables that live on stack of some_function
int x = 1;
int y = 2;
void (*foo)(int) = [](int someInt)
{
cout << "value passed to lambda is:" << someInt << endl;
};
// point global variables to variables created on this stack x,y and foo
_X = &x;
_Y = &y;
_F = foo;
// works
_F(11);
// works
print_values();
// when exiting variables x,y and foo should be deleted
}
int main(void)
{
// call some function
some_function();
// DOES NOT WORK (makes sense)
print_values();
// WHY DOES THIS WORK? WHY FOO IS NOT DISTROYED LIKE X AND Y?
_F(10);
return 0;
}