2015-02-07 72 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