是否可以将 boost::any 或 boost::variant 与 boost::pool 一起使用?

Is it possible to use boost::any or boost::variant with a boost::pool?

boost::any:

我尝试编译并运行以下代码来测试它:

#include <boost/any.hpp>
#include <boost/pool/object_pool.hpp>

int main()
{
  boost::object_pool<boost::any> pool;
  boost::any *i = pool.malloc();
  *i = 1;

  boost::any *j = pool.construct(2);

  pool.destroy(i);
  pool.destroy(j);
}

但是它在 boost::any 析构函数中出现段错误。

boost::变体:

正在尝试编译和运行以下内容:

#include <boost/any.hpp>
#include <boost/pool/object_pool.hpp>
#include <boost/variant.hpp>

int main()
{
  typedef boost::variant<int, double> my_variant;

  boost::object_pool<my_variant> pool;
  my_variant *i = pool.malloc();
  *i = 1;

  my_variant *j = pool.construct(2);

  pool.destroy(i);
  pool.destroy(j);
}

我收到以下错误:

a.out: visitation_impl.hpp:207: typename Visitor::result_type boost::detail::variant::visitation_impl(int, int, Visitor&, VPCV, mpl_::true_, NBF, W*, S*) [with W = mpl_::int_<20>; S = boost::detail::variant::visitation_impl_step, boost::mpl::l_iter >; Visitor = boost::detail::variant::invoke_visitor

; VPCV = void*; NBF = boost::variant::has_fallback_type_; typename Visitor::result_type = bool; mpl_::true_ = mpl_::bool_]: Assertion `false' failed. Aborted (core dumped)

这是预期的行为吗? boost::pool 是否仅适用于简单的 C++ 类型,如 int、doble、float 等?

是的,增强池适用于两者。你只是用错了。

CAVEAT: There's really no use at all to use a pool allocator with boost::any because it will dynamically allocate the held value outside of the pool.

But this doesn't mean that you can't if you use it right.

malloc 只分配未初始化的内存。期望能够 向它分配 就好像它是该点所暗示的对象类型的全功能实例是你的错误。

T *i = pool.malloc();
new (i) T();

这修复了它:

Live On Coliru

#include <boost/pool/object_pool.hpp>
#include <boost/any.hpp>
#include <boost/variant.hpp>

template <typename T>
void run_test() {
    boost::object_pool<T> pool;

    T *i = pool.malloc();
    new (i) T();
    *i = 1;

    T *j = pool.construct(2);

    pool.destroy(i);
    pool.destroy(j);
}

int main() {
    run_test<boost::variant<int, double> >();
    run_test<boost::any>();
}

这在 asan/ubsan 和 valgrind 下也能正常运行。

奖金问题

Is this expected behavior? Does the boost::pool only work for simple C++ types like int, doble, float, etc?

对于 POD 类型或普通类型,您可以省略构造函数,就像在这些情况下允许 C++ 编译器省略它们一样。