2017-05-07 53 views
2

我试图使用Cereal来序列化没有默认构造函数的对象。直接存储这些对象或通过智能指针工作。然而, 当我把物体放入容器,它不再编译:谷物:反序列化没有默认构造函数的对象向量

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; 
} 

回答

0

据我了解的方式这个库的作品,有没有办法来反序列化的东西,不具有至少为动态分配对象的默认构造函数。

下这样做的逻辑是这样的:

  1. 你需要反序列化vector<Node>
  2. 为了做到这一点,你需要分配的内存适量
  3. 谷物不知道的构造函数并且不能正确地分配对象内存
  4. 为了提供适当的对象构建,它需要默认构造函数
+1

想象一下加载没有默认构造函数的类型的场景。谷物序列化的接口要求你传递一个引用到要用序列化数据实例化的对象。在没有默认构造函数的情况下,您(用户)必须已经在谷物甚至看到它之前初始化了这样的对象。另一种方法是让谷物做对象的实际构造,这只能在动态创建(即指针)对象时才会发生,这样谷物就可以预先加载参数传递给构造函数,如'load_and_construct'中所示。 – Azoth

相关问题