谷物:无默认构造函数的对象的矢量
Cereal: deserialize a vector of objects without default constructor
我正在尝试使用谷物在没有默认构造函数的情况下序列化对象。直接或通过智能指针来存储此类对象。然而,当我将对象放入容器中时,它不再编译:
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;
}
据我了解,库库的工作方式,没有办法使某些东西至少对于动态分配的对象没有默认的构造函数。
以下逻辑:
- 您需要进行
vector<Node>
的挑选 - 为了做到这一点,您需要分配适当数量的内存
- 谷物不知道构造函数,也不能单独正确分配对象内存
- 为了提供适当的对象构建,需要默认构造函数
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数