2016-09-17 47 views
1

我爲std :: function設置的目標丟失了,我不知道爲什麼我忽略了這個程序中的一些小錯誤。有人可以幫忙嗎?設置爲std :: function的目標丟失了

class Test向lambda類註冊一個lambda類,但是當試圖調用回調時,std :: function中設置的目標會丟失。

#include <iostream> 
#include <functional> 

using namespace std; 

class callback_store final 
{ 

    using callback_func_type = std::function<void()>; 

    public: 
    static callback_store instance() 
    { 
     static callback_store instance; 
     return instance; 
    } 

    void register_callback(callback_func_type func) 
    { 
     std::cout << "register_callback() <<<" << std::endl; 
     m_func = func; 

     // I am able to call the targets from here. 
     std::cout << "register_callback() func() " << std::endl; 
     func(); 
     std::cout << "register_callback() m_func() " << std::endl; 
     m_func(); 

     // some stats 
     std::cout << "register_callback() :: " << func.target_type().name() << std::endl; 
    } 

    void invoke_callback() 
    { 
     std::cout << "invoke_callback() <<< " << std::endl; 

     if (!m_func) 
     { 
      // This block is hit! Why 
      std::cout << "invoke_callback() :: m_func empty" << std::endl; 
      return; 
     } 

     return m_func(); 
    } 

    private: 
    callback_func_type m_func; 

}; 


class Test final 
{ 
    public: 
    Test() 
    { 
     callback_store::instance().register_callback([this](){do_test();}); 
    } 

    ~Test() 
    { 
     std::cout << "destructor" << std::endl; 
    } 

    private: 
    void do_test() 
    { 
     std::cout << "do_test() invoked !!" << std::endl; 
    } 

}; 

int main() 
{ 
    cout << "Hello World" << endl; 

    Test t; 

    callback_store::instance().invoke_callback(); 


    return 0; 
} 

輸出:

sh-4.3$ g++ -std=c++11 -o main *.cpp 
sh-4.3$ main 
Hello World 
register_callback() <<< 
register_callback() func() 
do_test() invoked !! 
register_callback() m_func() 
do_test() invoked !! 
register_callback() :: ZN4TestC4EvEUlvE_ 
invoke_callback() <<< 
invoke_callback() :: m_func empty 
destructor 
+2

你的單身實現破,但是所有的單例實現都被破壞了。不要使用單身人士。 –

+0

你的代碼永遠不會註冊你的回調。由於你的'instance()'函數返回'callback_store'對象的一個​​臨時拷貝*,所以你的註冊數據會進入臨時的,然後立即被銷燬。實際的「主要」單例對象'static callback_store instance'永遠不會獲得任何註冊。 – AnT

回答

6

我覺得問題是你實現你的單例類的方式。

public: 
static callback_store instance() 
{ 
    static callback_store instance; 
    return instance; 
} 

您正在返回的靜態對象的副本,而不是你應該使用

public: 
static callback_store& instance() 
{ 
    static callback_store instance; 
    return instance; 
} 

您的代碼的輸出將被(測試):

Hello World 
register_callback() <<< 
register_callback() func() 
do_test() invoked !! 
register_callback() m_func() 
do_test() invoked !! 
register_callback() :: ZN4TestC4EvEUlvE_ 
invoke_callback() <<< 
do_test() invoked !! 
destructor 
4

實例()成員函數應該返回callback_store &

+0

解釋會很好,如果你可以添加一個:)此外,你應該包括額外的信息,也許鏈接到文檔? – Rakete1111