c++ - return lambda by rvalue ref? -


#include <iostream> #include <functional>  template <typename... args> std::function<void(args...)> pushtoeventloop(std::function<void(args...)> && p_function) {     auto func = [p_function](args... args) ->void     {         // here, requires source code         //threadpool::enque(std::bind(p_function, args...));         // i'll sake of example.         p_function(args...);     };     return func; }  int main()  {     auto function(pushtoeventloop(std::function<void(char const *)>(std::bind(std::printf, std::placeholders::_1))));      auto function2 = std::bind(function, "hello world!\n");      function2();      return 0; } 

is possible , how, return "func" variable rvalue ref?

i have feeling somehow totally insane, i'd know why, can restore sanity.

i have no idea if have done horribly wrong. please provide feedback.

i built thing can make callbacks posted treadpool processing, without caller or target knowing this. middleman binds them makes choice of how connect them.

https://ideone.com/4wfhb1


edit

ok, thought there copying going on when return func variable. apparently it's dealt rvo, no copying takes place. have not verified this, think it, make sense.

if question how return lamba in eficient way, return value , use automatic return typ deduction:

//this return lmabda , not std::function template <typename... args> auto pushtoeventloop(std::function<void(args...)> && p_function) {     return [f = std::move(p_function)](args... args)     {                    f(args...);     }; } 

this leverage rvo , avoid dynamic memory allocations std::function might have perform.

also having r-value reference parameter doesn't gain anything, if don't move (unless require specific interface reason). in order here can leverage c++14's generalized lambda capture (the compiler can't perform optimization itself, p_function l-value).

now, if question on other hand was, if/how can return (r- or l-value) reference non-static local variable function, answer simply:

never that!


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -