使用 boost::bind 创建绑定自动释放"heap"资源的函数对象

Using boost::bind to create a function object binding a auto-release "heap" resource

本文关键字:heap 资源 函数 对象 释放 bind boost 创建 绑定 使用      更新时间:2023-10-16

我尝试使用boost::bind来创建一个函数对象,同时,我想将在HEAP上创建的对象绑定到它以进行延迟调用。示例代码如下:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>
using namespace boost;
class CTest : public noncopyable
{
public:
    CTest():mInt(0){ std::cout << "constructor" << std::endl; }
    ~CTest(){ std::cout << "destructor" << std::endl; }
    int mInt;
};
int getM( CTest * t )
{
    return t->mInt;
}
function<int()> makeF()
{
    // create some resource on HEAP, not on STACK.
    // cause the STACK resource will be release after
    // function return.
    BOOST_AUTO( a , make_shared<CTest>() );
    // I want to use bind to create a function call
    // wrap the original function and the resource I create
    // for delay call.
    //
    // I use shared_ptr to auto release the resource when
    // the function object is gone.
    //
    // Compile ERROR!!! 
    // cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'CTest *'
    //
    return bind<int>( getM , a );
}

int main(int argc, char* argv[])
{
    BOOST_AUTO( delayFunc , makeF() );
    delayFunc();
    return 0;
}

以上只是一个示例代码。但我认为它显示了我想要的,当前错误是。

目前,我认为我只能使用函数对象来包装原始函数,如下所示:

class CGetM
{
public:
    typedef int result_type;
    int operator() ( shared_ptr<CTest> t )
    {
        return getM( t.get() );
    }
};

并替换如下代码:

return bind<int>( CGetM() , a );

然而,如果目前我有许多像getM这样的原始函数,为了适应正确的参数,将其包装在函数对象中确实是一项很大的工作。我不知道boost中是否有一些技巧或其他有用的实用类可以更智能、更优雅地处理这种情况?

所以任何建议都是赞赏的。谢谢。

你需要使用bind composition:

return bind<int>( getM, bind(&shared_ptr<CTest>::get, a) );