谷物:无默认构造函数的对象的矢量

Cereal: deserialize a vector of objects without default constructor

本文关键字:对象 构造函数 默认 谷物      更新时间:2023-10-16

我正在尝试使用谷物在没有默认构造函数的情况下序列化对象。直接或通过智能指针来存储此类对象。然而,当我将对象放入容器中时,它不再编译:

error: no matching function for call to ‘Node::Node()’

有没有办法让谷物存储/还原物体的向量,而无需默认构造函数?

我的测试代码:

#include <fstream>
#include <cereal/archives/json.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/vector.hpp>

class Node {
public:
    Node(int* parent) {};
    int value_1;
    template<class Archive>
    void serialize(Archive& archive) {
        archive(
                CEREAL_NVP(value_1)
        );
    }
    template<class Archive>
    static void load_and_construct(Archive& archive, cereal::construct<Node>& construct) {
        construct(nullptr);
        construct->serialize(archive);
    }
};
int main() {
    std::string file_path = "../data/nodes.json";
    Node node_1{nullptr};  // this would serialize
    std::vector<Node> nodes;  // this does not
    nodes.push_back(Node{nullptr});
    nodes.push_back(Node{nullptr});
    std::vector<std::unique_ptr<Node>> node_ptrs;  // this would serialize
    node_ptrs.push_back(std::make_unique<Node>(nullptr));
    node_ptrs.push_back(std::make_unique<Node>(nullptr));
    {  //store vector
        std::ofstream out_file(file_path);
        cereal::JSONOutputArchive out_archive(out_file);
        out_archive(CEREAL_NVP(nodes));
    }
    {  // load vector
        std::ifstream in_file(file_path);
        cereal::JSONInputArchive in_archive(in_file);
        in_archive(nodes);
    }
    return 0;
}

据我了解,库库的工作方式,没有办法使某些东西至少对于动态分配的对象没有默认的构造函数。

以下逻辑:

  1. 您需要进行vector<Node>
  2. 的挑选
  3. 为了做到这一点,您需要分配适当数量的内存
  4. 谷物不知道构造函数,也不能单独正确分配对象内存
  5. 为了提供适当的对象构建,需要默认构造函数