C++ 促进序列化、构造函数和数据复制
C++ Boost serialization, constructor and data copying
我试图了解 boost 库的序列化是如何工作的,我想确保我的想法正确。
如果我保存对象(我只有指向此对象的指针),然后尝试加载它,则顺序如下:
- 调用此对象的构造函数。
- 复制数据。
问题是,如果构造函数使用类的静态成员(例如一些计数器),它会给我有关加载对象的误导性信息。我有基于静态计数器的对象 ID,并且(加载后)构造函数打印到控制台的对象 ID 不正确。它似乎对我的程序没有伤害,因为在调用构造函数之后一切正常。甚至析构函数也会向我打印正确的对象 ID。
我对这个序列说得对吗?或者也许这里正在发生其他一些"魔术"?
如果我保存对象(我只有指向此对象的指针),然后尝试加载它,>顺序如下:
- 调用此对象的构造函数。
- 复制数据。
你是对的。当 boost 序列化库加载数据时,首先调用默认构造函数,然后复制数据,只要使用成员函数模板serialize()
就可以复制数据。
下面是一个示例。您还可以看到执行结果:http://melpon.org/wandbox/permlink/xlzdnK0UnZo48Ms2
#include <fstream>
#include <string>
#include <cassert>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class Person {
public:
Person():id_(id_master_++) {
std::cout << "Person() id = " << id_ << " and id_master_ is incremented to " << id_master_ <<std::endl;
};
~Person() {
std::cout << "~Person() id = " << id_ << std::endl;
}
Person(std::string const& name, int age)
:id_(id_master_++),
name_(name),
age_(age) {
std::cout << "Person(std::string const&, int) id = " << id_ << " and id_master_ is incremented to " << id_master_ <<std::endl;
}
std::string const& name() const { return name_; }
int age() const { return age_; }
private:
static int id_master_;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, unsigned int /*version*/)
{
ar & name_;
ar & age_;
std::cout << "before store or load id = " << id_ << std::endl;
ar & id_; // *1
std::cout << "after store or load id = " << id_ << std::endl;
}
int id_;
std::string name_;
int age_;
};
int Person::id_master_;
int main()
{
{
Person p1("John", 25);
std::ofstream ofs("person.txt");
boost::archive::text_oarchive oa(ofs);
oa << p1;
}
{
std::ifstream ifs("person.txt");
boost::archive::text_iarchive ia(ifs);
Person p2;
ia >> p2;
assert(p2.name() == "John");
assert(p2.age() == 25);
}
}
对象的 id 被 *1 处的加载数据覆盖。
有害它似乎对我的程序没有伤害,因为在调用构造函数之后一切正常。
或不有害取决于您的情况。对象按预期反序列化,但在我的示例中,id_master_递增为 2。要注意这种行为。
相关文章:
- 矢量如何将数据复制到另一个矢量?
- 将矢量的数据复制到<MyStruct>矢量<MyStruct>的指针
- 将父类的子类的数据复制到具有相同父类的另一个类
- 使用 memcpy 将矢量数据复制到 wstring 的正确方法
- C++:传递指向函数中类的指针会导致数据复制?
- 将数据复制到磁盘上新位置的语法
- pybind11:如何包装以 std::vector<double> 为参数以避免数据复制的 C++ 函数
- 如何将数据复制到字节数组的某些部分
- 使用Sapera拍摄图像并将数据复制到矢量
- 如果strncpy将随机数据复制到缓冲区中会发生什么
- C++ 促进序列化、构造函数和数据复制
- 将一个通道数据复制到OpenCV中的另一个通道
- SSE将数据复制到变量
- doxygen将doxygen注释中的特定数据复制到markdown页面中
- 正在将指针指向的数据复制到另一个指针中
- 使用 CUDA 将大数据复制到 GPU 和从 GPU 复制大数据
- 尝试将.csv数据复制到c++中的结构时出现堆栈溢出错误
- 数据复制与封装
- 如何将 frontBuffer 数据复制到纹理 DirectX 9
- 更快地将数组中的数据复制到目标,同时应用缩放或偏移因子