设置为std :: function的目标将丢失

时间:2016-09-17 17:20:00

标签: c++ c++11 lambda callable std-function

我为std :: function设置的目标已丢失,我不知道为什么我可能会忽略此程序中的一些小错误。有人可以帮忙。

class Test将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 :(得分: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

答案 1 :(得分:4)

instance()成员函数应返回callback_store&amp;