提升序列化不适用于shared_ptr<int>

Boost serialization doesn't work with shared_ptr<int>

本文关键字:lt int gt ptr 序列化 升序 不适用 适用于 shared      更新时间:2023-10-16

下面这段代码可以正常编译:

#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