加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在std ::函数中存储非复制但可移动的对象

发布时间:2020-12-16 07:51:00 所属栏目:百科 来源:网络整理
导读:假设我有一个函数,它是非复制但是可移动的,我该如何将它存储在std ::函数中?即如何编译以下代码? (使用 gcc 4.6) #include functional#include iostreamstruct S{ S() = default; S(S const) = delete; S operator=(S const) = delete; S(S) { } void oper
假设我有一个函数,它是非复制但是可移动的,我该如何将它存储在std ::函数中?即如何编译以下代码? (使用 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应该是可以复制的.因此,你不能直接实现你想要的.

不过,我可以用一些自定义包装来避免.它会这样的:

使你的包装器包含一个std :: shared_ptr给实际的函子;>当从函数rvalue构造包装器时,将函子移动到动态分配的内存;> wrapper和析构函数的复制构造函数只需要由shared_ptr copy-ctor / destructor处理;>运算符()为包装器取消引用智能指针到真正的函子和委托给它的operator().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读