Search code examples
c++classc++11function-pointersstd-function

Passing a member function of another class into a std::function parameter


I have a class with a function that takes a std::function and stores it. This part seems to compile ok (but please point out any issue if there are any)

#include <functional>
#include <iostream>

struct worker
{
   std::function<bool(std::string)> m_callback;
   void do_work(std::function<bool(std::string)> callback)
   {
      m_callback = std::bind(callback, std::placeholders::_1);
      callback("hello world\n");
   }
};

// pretty boring class - a cut down of my actual class
struct helper
{
   worker the_worker;
   bool work_callback(std::string str)
   {
      std::cout << str << std::endl;
      return true;
   }
};

int main()
{
   helper the_helper;
   //the_helper.the_worker.do_work(std::bind(&helper::work_callback, the_helper, std::placeholders::_1));  // <---- SEGFAULT (but works in minimal example)
   the_helper.the_worker.do_work(std::bind(&helper::work_callback, &the_helper, std::placeholders::_1));  // <---- SEEMS TO WORK
}

I get a segfault, but I am not sure why. I have used this before, in fact, I copied this example from another place I used it. The only real difference that the member function was part of the class I called it from (i.e. this instead of the_helper).

So this is why I am also asking if there is anything else I am doing wrong in general? Like should I be passing the std::function as:

void do_work(std::function<bool(std::string)>&& callback)

or

void do_work(std::function<bool(std::string)>& callback)

Solution

  • As also noted by @Rakete1111 in comments, the problem probably was in this code:

    bool work_callback(std::string str)
    {
       std::cout << str << std::endl;
    }
    

    In C++ if a non-void function does not return a value the result is undefined behavior.

    This example will crash with clang but pass with gcc.

    If helper::work_callback returns (e.g, true) the code works just fine.