![](/img/trans.png)
[英]Boost Any to Boost Variant using Boost Preprocessor
[英]Is it possible to use boost::any or boost::variant with a boost::pool?
提升::任何:
我嘗試編譯並運行以下代碼來測試:
#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 析構函數中出現了段錯誤。
提升::變體:
嘗試編譯並運行以下命令:
#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 >; 訪客 = boost::detail::variant::invoke_visitor
; VPCV = 無效*; NBF = boost::variant::has_fallback_type_; typename 訪問者::result_type = bool; mpl_::true_ = mpl_::bool_]:斷言“false”失敗。 中止(核心轉儲)
這是預期的行為嗎? boost::pool 是否僅適用於簡單的 C++ 類型,如 int、doble、float 等?
是的,提升池適用於兩者。 你只是用錯了。
CAVEAT :使用帶有
boost::any
的池分配器真的沒有任何用處,因為它會在池外動態分配持有的值。但這並不意味着如果使用得當就不能。
malloc
只分配未初始化的內存。 期望能夠將其分配給它,就好像它是該點暗示的對象類型的全功能實例一樣,這是您的錯誤。
T *i = pool.malloc();
new (i) T();
這修復了它:
#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 下運行干凈。
這是預期的行為嗎? boost::pool 是否僅適用於簡單的 C++ 類型,如 int、doble、float 等?
對於 POD 類型或普通類型,您可以通過省略構造函數而逃脫,就像在這些情況下允許 C++ 編譯器省略它們一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.