gpt4 book ai didi

c++ - Boost序列化不适用于shared_ptr

转载 作者:行者123 更新时间:2023-12-02 10:30:40 28 4
gpt4 key购买 nike

以下代码可以很好地进行编译:

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

最佳答案

从关于该断言的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。

关于c++ - Boost序列化不适用于shared_ptr <int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62359010/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com