Boost序列化不适用于shared_ptr< int> [英] Boost serialization doesn't work with shared_ptr<int>

查看:124
本文介绍了Boost序列化不适用于shared_ptr< int>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码可以很好地编译:

The following piece of code compiles just fine:

#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,那么它也应该可以工作.

Now I would expect that if I replace A with int then it should also work.

#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;
}

但是,此代码不会编译,但是会导致断言失败:

However, this code doesn't compile, but gives an assertion failure:

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中的错误?

Am I doing something wrong or is this a bug in Boost?

推荐答案

有关该断言的Boost源代码:

From the Boost source code around that assertion:

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

Basically, in order to serialize things like shared_ptr properly, the pointed-to objects need to be centrally tracked during the serialization process (to identify when multiple pointers point to the same object, so they don't lead to two copies of the object being serialized). Tracking an object is more expensive than not tracking it, though, so primitive types are not tracked (the assumption being that there's gonna be a lot of them). Essentially, this makes it impossible to serialize shared_ptr<primitive_type> without mucking with the Boost sources. The solution, as the comment says, is to instead serialize some UDT containing an int.

这篇关于Boost序列化不适用于shared_ptr&lt; int&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆