gpt4 book ai didi

c++ - 提升 vector 序列化追加问题

转载 作者:行者123 更新时间:2023-11-30 05:34:56 25 4
gpt4 key购买 nike

考虑以下示例:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/serialization.hpp>


#include <iostream>
#include <sstream>

using namespace boost;
using namespace std;


int main()
{
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);



vector<int> src1 = {1}, src2 = {2};

vector<int> dst;

oa << src1;
oa << src2;

string serialized = oss.str();
std::istringstream iss(serialized);
boost::archive::text_iarchive ia(iss);


ia >> dst;

cout << "size=" << dst.size() << endl;

ia >> dst;
cout << "size=" << dst.size() << endl;
}

输出:
尺寸=1
尺寸=1

一切都很好。但是,如果将 vector 更改为 vector :

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/serialization.hpp>


#include <iostream>
#include <sstream>

using namespace boost;
using namespace std;


int main()
{
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);


vector<string> src1 = {"hi"}, src2 = {"hi"};

vector<string> dst;


oa << src1;
oa << src2;

string serialized = oss.str();
std::istringstream iss(serialized);
boost::archive::text_iarchive ia(iss);


ia >> dst;

cout << "size=" << dst.size() << endl;

ia >> dst;
cout << "size=" << dst.size() << endl;
}

输出:
尺寸=1
尺寸=2

结果附加到 dst,而不是赋值。为什么?如何实现“赋值语义”?

编译器:gcc 版本 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2)
编译:g++ -std=c++11 test2.cc -lboost_serialization

最佳答案

在 boost 1.58 的源代码中有以下代码。

if(detail::is_default_constructible<U>()){
t.resize(count);
typename std::vector<U, Allocator>::iterator hint;
hint = t.begin();
while(count-- > 0){
ar >> boost::serialization::make_nvp("item", *hint++);
}
}
else{
t.reserve(count);
while(count-- > 0){
detail::stack_construct<Archive, U> u(ar, item_version);
ar >> boost::serialization::make_nvp("item", u.reference());
t.push_back(u.reference());
ar.reset_object_address(& t.back() , & u.reference());
}
}

并且 detail::is_default_constructiblestd::string 返回 false(出于某些原因 boost::has_trivial_constructor 被使用)和 true 用于 int。因此,当 Uint 时,将调用 resize 然后使用赋值,但当 Ustd::string reserve 将被使用(reserve 实际上不调整容器的大小)然后 push_back 将被使用。

简单的解决方法是在第二次从存档中读取之前清除 vector。

ia >> dst;

cout << "size=" << dst.size() << endl;

dst.clear();
ia >> dst;
cout << "size=" << dst.size() << endl;

关于c++ - 提升 vector 序列化追加问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042933/

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