Why can't I grab the C ++ lambda function?

Say I have a boilerplate action

template <class ArgT> struct Action { Action(::boost::function< void(ArgT) > func) : func_(func) { } void operator()(ArgT arg) { func_(arg); } private: ::boost::function< void(ArgT) > func_; }; 

I use Action like this:

 class XCallbackInvoker : public CallbackInvoker< X > { public: XCallbackInvoker (Action< int > callback) : CallbackInvoker< X >( Action< ::boost::shared_ptr< X > >( [&callback](::boost::shared_ptr< X > x) -> void { Action< int > callbackCopy = callback; callbackCopy(x->errorCode()); })) { } }; 

Edit: Added CallbackInvoker

 template <class T> class CallbackInvoker : public ICallbackInvoker { public: CallbackInvoker(Action< ::boost::shared_ptr< T > > callback) : callback_(callback) { } void invoke(::boost::shared_ptr< IBase > message) { callback_(::boost::static_pointer_cast< T >(message)); } private: Action< ::boost::shared_ptr< T > > callback_; }; 

Now, if I don't use a temporary one to copy the value referenced by the callback, it compiles fine, but I get a runtime error (my callback is lost). If I pass my lambda the callback argument by value (that is, [=callback] ) and do not use a temporary one, I get a compilation error (my expression will lose some constants with volatile stability ...)

Why can't I grab my lambda function by value instead of using a temporary one?

+4
source share
1 answer

If you grabbed a copy, you cannot change it by default, since operator() lambda is declared const . You need to add mutable to your lambda to allow modifications to the captured variables:

 XCallbackInvoker (Action< int > callback) : CallbackInvoker< X >( Action< ::boost::shared_ptr< X > >( [callback](::boost::shared_ptr< X > x) mutable -> void { callback(x->errorCode()); })) { } 
+11
source

All Articles