我不确定我是否定义了以下情况下的行为:
我的函数指针类型:
typedef void (*DoAfter_cb_type)(void);
应该分配回调的函数:
void DoSomething(DoAfter_cb_type & DoAfter_cb)
{
//...
DoAfter_cb = [](){
//...
};
}
来电者:
DoAfter_cb_type DoAfter_cb = nullptr;
DoSomething(DoAfter_cb);
// Here is something that has to be done after DoSomething but before DoAfter_cb.
if( DoAfter_cb != nullptr){
DoAfter_cb();
}
据我了解here lambda 可以隐式转换为函数指针。
然而,它们仍然是指针,我担心调用 lambda 的一些重要内容存储在堆栈中,如果我只返回函数指针,它们将超出范围
我必须使用函数指针,因为我无法在我的环境中访问 std::function。 使用 std::function 我希望 lambda 对象存储在引用变量中,我不会有任何问题。
行为是否与如果我只定义一个普通函数相同,或者我在这里有任何副作用吗?
最佳答案
Is the behaviour the same as If I would just define an ordinary function or do I have any side effects here?
是的,是一样的。无捕获 lambda 可转换为常规函数指针,因为引用 C++ 标准([expr.prim.lambda.closure]/6,强调我的):
The closure type for a non-generic lambda-expression with no lambda-capture has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator. The conversion is to “pointer to noexcept function” if the function call operator has a non-throwing exception specification. The value returned by this conversion function is the address of a function F that, when invoked, has the same effect as invoking the closure type's function call operator.
因此,当 lambda 超出范围时,该指针由适当的函数支持,就像您在文件范围内自己编写它一样。函数在整个程序执行过程中都“有效”,因此指针始终有效。
关于c++ - 将 C++ lambda 复制到函数指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49666616/