在std :: function中存储不可复制但可移动的对象 [英] Storing noncopyable but movable object in std::function

查看:205
本文介绍了在std :: function中存储不可复制但可移动的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数s,它是不可复制但可移动的,我如何将它存储在std ::函数?即,如何使下面的代码编译? (使用gcc 4.6)

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)

#include <functional>
#include <iostream>

struct S
{
  S() = default;
  S(S const&) = delete;
  S& operator=(S const&) = delete;
  S(S&&) { }
  void operator()() { }
};

std::function<void()> func;

void make_func()
{
  S s;
  func = std::bind(std::move(s));  // This won't compile
}

int main()
{
  make_func();
}


推荐答案

标准, std :: function 应该是可复制的。因此,您无法直接达到您想要的效果。

As far as I understand the standard, std::function is supposed to be copyable. Therefore, you cannot directly achieve what you want.

您可以使用一些自定义封装,它会像这样:

You can get away with some custom wrapper I'd guess, though. It would go something like this:


  • 使你的包装包含 std :: shared_ptr 到实际函子;

  • 当函数从右边构造一个包装器时,将函子移动到动态分配的内存中;

  • 复制构造函数包装和析构函数由 shared_ptr copy-ctor / destructor;

  • c $ c>为封装器解除引用到真实函数的智能指针,并委托 operator()

  • make your wrapper contain an std::shared_ptr to the actual functor;
  • when a wrapper is constructed from a functor rvalue, move the functor to dynamically allocated memory;
  • copy constructor for the wrapper and destructor are simply handled by shared_ptr copy-ctor/destructor;
  • operator() for the wrapper dereferences the smart pointer to the real functor and delegates to operator() on it.

这篇关于在std :: function中存储不可复制但可移动的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆