为什么C ++ 11不能将不可复制的函子移动到std ::函数? [英] Why can't C++11 move a noncopyable functor to a std::function?

查看:106
本文介绍了为什么C ++ 11不能将不可复制的函子移动到std ::函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  // ------------------------------------ ------------------------------------------ 
struct A
{
A(){}
A(A&& amp;){}
A& operator =(A&&){return * this;}
void operator()(){}

private:
A(const A&
A& operator =(const A&);

int x;
};

// ---------------------------------------- --------------------------------------
int main()
{
A a;
std :: function< void()> func(std :: move(a));
}

'A :: A':无法访问在'A' '



当我通过引用或 const 捕获某个东西时,我可以创建一个不可复制的lambda。但是当我这样做它实际上是工作给它一个 std :: function

解决方案

简单的答案是,C ++ 11规范要求您的 A CopyConstructible 可以使用 std :: function



很长的答案是存在这个要求,因为 std :: function 删除构造函数中函数的类型。为此, std :: function 必须通过虚函数访问函子的某些成员。这些包括调用操作符,复制构造函数和析构函数。因为这些是通过虚拟调用访问的,无论是否实际使用 std :: function 的复制构造函数,析构函数或调用操作符,它们都被使用。


//------------------------------------------------------------------------------
struct A
{
    A(){}
    A(A&&){}
    A& operator=(A&&){return *this;}
    void operator()(){}

private:
    A(const A&);
    A& operator=(const A&);

    int x;
};

//------------------------------------------------------------------------------
int main()
{
    A a;
    std::function<void()> func(std::move(a));
}

'A::A' : cannot access private member declared in class 'A'

It seems like when I capture something by reference or const I can make a non-copyable lambda. However when I do that it actually works to give it to a std::function.

解决方案

The short answer is that the C++11 specification requires your A to be CopyConstructible to be used with std::function.

The long answer is this requirement exists because std::function erases the type of your functor within the constructor. To do this, std::function must access certain members of your functor via virtual functions. These include the call operator, the copy constructor and the destructor. And since these are accessed via a virtual call, they are "used" whether or not you actually use std::function's copy constructor, destructor or call operator.

这篇关于为什么C ++ 11不能将不可复制的函子移动到std ::函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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