samedi 12 septembre 2020

segment fault when passing right reference for literal in labmda with varidic template function

the code is as follows

#include <functional>
#include <iostream>

using namespace std;
int foo(int a){
    cout<<a;
    return a;
}

template<typename R, typename ...Args>
function<void()> wrapper( R f, Args&& ... args) {
    function<void()> fun([&] { f(forward<Args...>(args...)); });//crash
    //function<void()> fun=bind(f,forward<Args...>(args...));
    return fun;
}

int main(){
    auto d=wrapper(foo,1);
    d();
    return 0;
}

when I use bind, all is fine. but when I use lambda the program crash. I wonder there is a way to capture variable by reference for lambda but capture literal by value(for efficiency)? Or should I stick with bind?

Aucun commentaire:

Enregistrer un commentaire