home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,592 of 33,346   
   =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to Ralph Zhang   
   Re: Storing noncopyable but movable obje   
   31 Oct 11 23:11:23   
   
   b02910e3   
   From: daniel.kruegler@googlemail.com   
      
   On 2011-10-31 06:43, Ralph Zhang wrote:   
   > Suppose I have a functor s, which is noncopyable but movable, how can   
   > I store it in a std::function? i.e, how to make the following code   
   > compile? (using gcc 4.6)   
      
   First of all, you don't need std::bind in your example, the assignment   
   of a callable functor to std::function can be done directly as   
      
    func = std::move(s);   
      
   This doesn't solve your problem though. There exists a fundamental   
   requirement, that the wrapped functor is CopyConstructible. This is   
   related to the fact, that std::function performs type-erasure on the   
   wrapped function object. So, if you need to wrap your move-only functor   
   anyway, you either need to wrap a reference of it (e.g. using   
   std::reference_wrapper) or you need to perform dynamic memory allocation   
   and user a wrapping function object of your move-only functor e.g.   
      
   struct WS   
   {   
     std::shared_ptr ps;   
     void operator()() { (*ps)(); }   
   };   
      
   It depends on the life-cycle of the std::function wrapper, whether you   
   can use the reference_wrapper approach (Obviously you cannot return an   
   automatic variable of S out of the function scope), or whether you need   
   to use dynamic memory allocation.   
      
   HTH & Greetings from Bremen,   
      
   Daniel Krügler   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca