2015-02-07 71 views
0

我想使用函数指针到类成员函数,然后使用std :: bind来调用该函数在一个单独的函数中关于该类的一个对象。在这个单独的函数中,我可以绑定对象和函数指针一次,然后第二次在Xcode中,但不与MSVS2015 ...试图重新分配std ::功能与std :: bind并获取错误“尝试引用已删除的功能”

这里是一些基本代码,重现我遇到的问题。一切编译和运行上的Xcode罚款:

class AClass 
{ 
public: 
    bool isNumber1() 
    { 
     return num == 1 ? true : false; 
    } 

private: 
    int num; 
}; 

typedef bool (AClass::*isFunction)(); 

bool checkIsFunc (AClass& object, isFunction function) 
{ 
    auto f = std::bind(function, object); 

    f = std::bind(function, object); // Error occurs here 

    return f(); 
} 

int main (int argc, char* argv[]) 
{ 

    AClass obj; 

    bool outcome = checkIsFunc(obj, &AClass::isNumber1); 

    return 0; 
} 

然而,随着MSVS2015,我得到以下错误:

error C2280: 'std::_Bind<true,bool,std::_Pmf_wrap<bool (__thiscall AClass::*)(void),bool,AClass,>,AClass &> &std::_Bind<true,bool,std::_Pmf_wrap<bool (__thiscall AClass::*)(void),bool,AClass,>,AClass &>::operator =(const std::_Bind<true,bool,std::_Pmf_wrap<bool (__thiscall AClass::*)(void),bool,AClass,>,AClass &> &)': attempting to reference a deleted function 

任何想法,我做错了什么,或者为什么这个工程在Xcode而不是VS ?

谢谢!

吉姆

回答

1

std::bind没有返回std::function对象,但实现定义粘结剂类型之一。在这里,那么:

auto f = std::bind(function, object); 

f被推断为这种粘合剂类型,而这种粘结剂类型没有可分配,只可复制构造和MoveConstructible。答曰标准,[func.bind.bind]/5:

Remarks: The return type [of std::bind] shall satifsy the requirements of MoveConstructible . If all of FD and TiD satisfy the requirements of CopyConstructible , then the return type shall satisfy the requirements of CopyConstructible .

FDTiD分别结合的功能类型和参数类型。请注意,它没有提到MoveAssignableCopyAssignable,这意味着没有要求活页夹满足它们。这意味着分配

f = std::bind(function, object); // Error occurs here 

是标准没有要求的工作。

看来,MSVC的std::bind坚持这一点,而libC++(我相信与Xcode一起提供,但我不为Mac OS X开发)更宽松。

如果你想f成为std::function,你必须将其声明为我们明确:

std::function<bool()> f = std::bind(function, object); 

然后重新分配也能发挥作用,因为std::function是分配。

与这样的要求没有提到别的

+0

啊随时随地的事实一起,我开始得出这样的结论。我试图找出绑定返回的内容,然后想要制作一个指针,稍后我会在执行过程中更新它。一旦我创建了一个std ::函数,你就回应了!再次感谢! – jimspree1200 2015-02-07 13:53:48