pet*_*ohn 3 c++ boost boost-serialization
以下代码编译得很好:
#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;
}
Run Code Online (Sandbox Code Playgroud)
现在我希望如果我替换A它int那么它也应该工作.
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码无法编译,但会导致断言失败:
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(
^
...
Run Code Online (Sandbox Code Playgroud)
我做错了什么或者这是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));
Run Code Online (Sandbox Code Playgroud)
基本上,为了shared_ptr正确地序列化事物,在序列化过程中需要集中跟踪指向的对象(以识别多个指针何时指向同一个对象,因此它们不会导致被序列化的对象的两个副本).但是,跟踪对象比不跟踪对象更昂贵,因此不会跟踪原始类型(假设它们中的很多都会被跟踪).从本质上讲,这使得无法在shared_ptr<primitive_type>不使用Boost源的情况下进行序列化.正如评论所说,解决方案是将一些包含 int的UDT序列化.
| 归档时间: |
|
| 查看次数: |
347 次 |
| 最近记录: |