分配给 boost 函数的 class 实例的 boost ref

boost ref of an instance of a class assigned to boost function

我遇到了以下代码,其中 Foo 是任何用户定义的 class:

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

我有以下问题: 1. 如果将 class 的实例分配给 boost 函数指针会怎样?我以为我们只能给它分配功能。 2. 为什么发送 boost ref 而不仅仅是值?

  1. boost::function(和 C++11 的 std::function)换行 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. boost::function documentation 解释了为什么您可能想要包装对函子的引用而不是函数本身:

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: