C++ 促进序列化、构造函数和数据复制

C++ Boost serialization, constructor and data copying

本文关键字:数据 复制 构造函数 序列化 C++      更新时间:2023-10-16

我试图了解 boost 库的序列化是如何工作的,我想确保我的想法正确。

如果我保存对象(我只有指向此对象的指针),然后尝试加载它,则顺序如下:

  1. 调用此对象的构造函数。
  2. 复制数据。

问题是,如果构造函数使用类的静态成员(例如一些计数器),它会给我有关加载对象的误导性信息。我有基于静态计数器的对象 ID,并且(加载后)构造函数打印到控制台的对象 ID 不正确。它似乎对我的程序没有伤害,因为在调用构造函数之后一切正常。甚至析构函数也会向我打印正确的对象 ID。

我对这个序列说得对吗?或者也许这里正在发生其他一些"魔术"?

如果我保存对象(我只有指向此对象的指针),然后尝试加载它,>顺序如下:

  1. 调用此对象的构造函数。
  2. 复制数据。

你是对的。当 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。要注意这种行为。