根据我的经验,似乎要么:
std::function从lambda中创建一个临时对象(std :: function),并在调用后销毁该对象使用以下代码片段可以观察到此行为:
const function<void()>* pointer;
void a(const function<void()> & f)
{
pointer = &f;
}
void b()
{
(*pointer)();
}
int main()
{
int value = 1;
std::cout << &value << std::endl;
// 1: this works
function<void()> f = [&] () { std::cout << &value << std::endl; };
a(f);
// 2: this doesn't
a([&] () { std::cout << &value << std::endl; });
/* modify the stack*/
char data[1024];
for (int i = 0; i …Run Code Online (Sandbox Code Playgroud)