c++ - 如何将 boost::object_pool<>::construct 与非 const 引用一起用作 ctor 参数?

标签 c++ boost memory-management pool

是否可以通过非 const 引用使用 boost::object_pool<>::construct?

以下代码段无法编译 (VS2010):

foo::foo(bar & b)
{
}

static boost::shared_ptr<foo> foo::create(bar & b)
{
  return boost::shared_ptr<foo>(foo_pool.construct(b),
    boost::bind(& boost::object_pool<foo>::destroy, & foo_pool, _1));
}

VS2010 提示无法将 bar & 转换为 const bar &。查看 boost::object_pool<>::construct 原因很清楚:

element_type * construct(const T0 & a0)

虽然我不能使 ctor 参数为 const。有什么技巧可以让 boost::object_pool<> 与我的 foo 类一起工作吗?

最佳答案

使用boost::ref :

static boost::shared_ptr<foo> foo::create(bar & b)
{
  return boost::shared_ptr<foo>(foo_pool.construct(boost::ref(b)),
    boost::bind(& boost::object_pool<foo>::destroy, & foo_pool, _1));
}

boost::ref 生成一个 reference_wrapper。因为它使用指针,所以可以随心所欲地复制它,并隐式取消引用为对原始值的引用。

关于c++ - 如何将 boost::object_pool<>::construct 与非 const 引用一起用作 ctor 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3455493/

相关文章:

c++ - 如何创建代理类?

c++ - libboost_regex 未编译

c++ - 基于宏的计数器

c - C 中 realloc() 的问题。总是挂起但编译正常

c++ - 为什么在空指针上调用 "operator delete"时会调用 "delete"?

c++命令行宏预处理器无法替换单词

c++ - 在这种情况下,为什么编译器会抛出 “undefined reference to…”错误?

c++ - 将字符串转换为 Const Char XYZ[] PROGMEM {}

c++ - 在编译的二进制文件中包含 CSV 文件

c# - 我应该使用静态方法还是非静态方法?