提升序列化不适用于shared_ptr<int>
Boost serialization doesn't work with shared_ptr<int>
下面这段代码可以正常编译:
#include <boost/serialization/shared_ptr.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <sstream>
#include <memory>
struct A {
int i;
A(): i(0) {}
A(int i): i(i) {}
template <typename Archive>
void serialize(Archive& ar, const unsigned int) {
ar & i;
}
};
int main() {
auto a = std::make_shared<A>(465);
std::stringstream stream;
boost::archive::text_oarchive out{stream};
out << a;
}
现在我希望,如果我用int
代替A
,那么它也应该工作。
#include <boost/serialization/shared_ptr.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <sstream>
#include <memory>
int main() {
auto a = std::make_shared<int>(465);
std::stringstream stream;
boost::archive::text_oarchive out{stream};
out << a;
}
但是,这段代码不能编译,而是给出了一个断言失败:
In file included from main.cpp:1:
/usr/local/include/boost/serialization/shared_ptr.hpp:277:5: error: static_assert failed "boost::serialization::tracking_level< T >::value != boost::serialization::track_never"
BOOST_STATIC_ASSERT(
^
...
我做错了什么还是这是一个bug在Boost?
从Boost源代码周围的断言:
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
基本上,为了正确地序列化像shared_ptr
这样的东西,在序列化过程中需要集中跟踪指向的对象(以识别多个指针何时指向同一对象,因此它们不会导致对象的两个副本被序列化)。但是,跟踪对象比不跟踪对象代价更大,因此不跟踪基本类型(假设将有大量基本类型)。从本质上讲,这使得不可能在不搅乱Boost源的情况下序列化shared_ptr<primitive_type>
。正如注释所说,解决方案是序列化一些包含和int的UDT 。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 呼叫运营商<<临时
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 运营商&lt;&lt;无法访问班级的私人int
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- 如何显示/打印字符串对象?cout & lt; & lt;Int工作,count <<字符串