Boost序列化不适用于shared_ptr <int>

时间:2015-08-17 19:21:03

标签: 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;
}

现在我希望如果我将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;
}

但是,这段代码没有编译,但断言失败:

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(
    ^
...

我做错了什么或者这是Boost中的错误?

1 个答案:

答案 0 :(得分:5)

围绕该断言的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之类的东西,需要在序列化过程中集中跟踪指向对象(以识别多个指针指向同一个对象的时间,因此它们不会“ t导致被序列化的对象的两个副本)。然而,跟踪对象比不跟踪对象更昂贵,因此不跟踪原始类型(假设它们将是很多)。从本质上讲,这使得无法在不使用Boost源的情况下序列化shared_ptr<primitive_type>。正如评论所说,解决方案是序列化一些包含 int的UDT