如何使用 boost::object_pool<>::construct 并将非常量引用作为构造函数参数?

发布于 2024-09-13 14:53:00 字数 602 浏览 4 评论 0 原文

是否可以以某种方式将 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栏&。看看 boost::object_pool<>::construct ,原因很清楚:

element_type * construct(const T0 & a0)

但我无法将 ctor 参数设置为 const。有没有办法让 boost::object_pool<>与我的 foo 类一起工作吗?

Is it somehow possible to use boost::object_pool<>::construct with non const references?

The following snippet doesn't compile (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 complains about not being able to convert bar & to const bar &. Looking at boost::object_pool<>::construct the reason ist clear:

element_type * construct(const T0 & a0)

I can't make the ctor parameter const though. Is there a trick to make boost::object_pool<> work with my foo class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

比忠 2024-09-20 14:53:00

使用 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。因为它使用指针,所以可以根据需要进行复制,并隐式取消引用为对原始值的引用。

Use 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 makes a reference_wrapper. Because that uses a pointer, it can be copied around however you wish, and implicitly dereferenced into a reference to the original value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文