lambda - Retaining a pointer by extending the life of capture -
this question has answer here:
is possible extend life of unique_ptr
capturing in lambda , extending life of lambda?
i tried out getting syntax errors a=move(a)
expression.
#include <cstdio> #include <functional> #include <memory> #include <iostream> using namespace std; struct { a() { cout << "a()" << endl; } ~a() { cout << "~a()" << endl; } }; int main() { std::function<void ()> f; { std::unique_ptr<a> a(new a()); f = [a=move(a)] () mutable { return; }; } return 0; }
well problem code std::function
. not move friendly needs callable copy constructible/assignable lambda not because of use of move type, unique_ptr
in example.
there many examples out there can provide move friendly version of std::function
.
i have come here quick, hacky, , error prone "working on machine" version of same:
#include <memory> #include <iostream> #include <type_traits> struct { a() { std::cout << "a()" << std::endl; } ~a() { std::cout << "~a()" << std::endl; } }; template <typename functor> struct holder { static void call(char* sbo) { functor* cb = reinterpret_cast<functor*>(sbo); cb->operator()(); } static void deleter(char* sbo) { auto impl = reinterpret_cast<functor*>(sbo); impl->~functor(); } }; template <typename sign> struct function; template <> struct function<void()> { function() = default; ~function() { deleter_(sbo_); } template <typename f> void operator=(f&& f) { using c = typename std::decay<f>::type; new (sbo_) c(std::forward<f>(f)); call_fn_ = holder<c>::call; deleter_ = holder<c>::deleter; } void operator()() { call_fn_(sbo_); } typedef void(*call_ptr_fn)(char*); call_ptr_fn call_fn_; call_ptr_fn deleter_; char sbo_[256] = {0,}; }; int main() { function<void()> f; { std::unique_ptr<a> a(new a()); f = [a=move(a)] () mutable { return; }; } std::cout << "destructor should not called before this" << std::endl; return 0; }
to try out yourself: http://coliru.stacked-crooked.com/a/60e1be83753c0f3f
Comments
Post a Comment