Re: Storing noncopyable but movable object in std::function
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<S> 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! ]