使用 boost::bind 创建绑定自动释放"heap"资源的函数对象
Using boost::bind to create a function object binding a auto-release "heap" resource
我尝试使用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) );
相关文章:
- 具有瞬态资源的RAII类
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 允许从 std::map 的密钥窃取资源?
- 参考资源文件VC++中的$(SolutionDir)
- 如何维护资源管理器项目视图中当前可见的项目列表
- 将 std::allocate_shared 与多态资源分配器一起使用
- 使用RAII在给定次数的迭代后重新分配资源
- 资源管理设计模式
- 如何跨平台将二进制资源构建到程序中?
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- SetDlgItemInt 不会更改嵌入资源的编辑框
- Klocwork Inside的资源泄漏
- 从存储为 Windows 资源 (c++) 的 png 中获取 png 文件数据
- C++链接时间资源"allocation"而不定义
- 使用 Bazel 生成 QT 资源文件
- 编译器资源管理器和 GCC 具有不同的输出
- 当为可变性配置时,boost::heap::d_ary_heap 保留的额外 std::list 的目的是什么?
- 使用 Bazel 编译 QT 应用程序时访问资源
- 根据需要声明资源,而不重复它们
- 使用 boost::bind 创建绑定自动释放"heap"资源的函数对象