0

I came across the following code where Foo is any user-defined class:

boost::function<return_type (parameter)> f = boost::ref(instanceOfFoo);

And I have the following Qs: 1. What happens if you assign an instance of a class to the boost function pointer? I thought we could only assign functions to it. 2. Why is the boost ref sent and not just the value?

simplename
  • 717
  • 7
  • 15

1 Answers1

1
  1. boost::function (and C++11's std::function) wrap callable objects, which are any object that can be invoked like a function. This includes both ordinary functions and functors. A functor is a class or struct that that defines operator().

  2. The boost::function documentation explains why you might want to wrap a reference to a functor instead of the function itself:

In some cases it is expensive (or semantically incorrect) to have Boost.Function clone a function object. In such cases, it is possible to request that Boost.Function keep only a reference to the actual function object. This is done using the ref and cref functions to wrap a reference to a function object:

Community
  • 1
  • 1
rhashimoto
  • 15,650
  • 2
  • 52
  • 80
  • So effectively, assigning a functor instance to a boost function pointer is like assigning the operator()() "function" to it? Thanks – simplename Jul 15 '16 at 17:00
  • 1
    Yes, but take note that you are binding not only the `operator()` member function but also the member variable state of the instance that the function may use. – rhashimoto Jul 15 '16 at 17:22