【问题标题】:yaml-cpp encoding / decoding pointers?yaml-cpp 编码/解码指针?
【发布时间】:2018-06-12 00:22:33
【问题描述】:

所以我正在尝试将 yaml-cpp 与包含指针的数据一起使用,这是我的代码:

struct InventoryItem {
  std::string name;
  int baseValue;
  float weight;
};

struct Inventory {
  float maximumWeight;
  std::vector<InventoryItem*> items;
};

namespace YAML {
template <>
struct convert<InventoryItem*> {
  static Node encode(const InventoryItem* inventoryItem) {
    Node node;

    node["name"] = inventoryItem->name;
    node["baseValue"] = inventoryItem->baseValue;
    node["weight"] = inventoryItem->weight;

    return node;
  }

  static bool decode(const Node& node, InventoryItem* inventoryItem) {
    // @todo validation
    inventoryItem->name = node["name"].as<std::string>();
    inventoryItem->baseValue = node["baseValue"].as<int>();
    inventoryItem->weight = node["weight"].as<float>();

    return true;
  }
};

template <>
struct convert<Inventory> {
  static Node encode(const Inventory& inventory) {
    Node node;

    node["maximumWeight"] = inventory.maximumWeight;
    node["items"] = inventory.items;

    return node;
  }

  static bool decode(const Node& node, Inventory& inventory) {
    // @todo validation
    inventory.maximumWeight = node["maximumWeight"].as<float>();
    inventory.items = node["items"].as<std::vector<InventoryItem*>>();

    return true;
  }
};
}

但我收到以下错误:

impl.h(123): error C4700: uninitialized local variable 't' used

引用此代码块中的最后一个 if 语句(此代码在 yaml-cpp 库中:

template <typename T>
struct as_if<T, void> {
  explicit as_if(const Node& node_) : node(node_) {}
  const Node& node;

  T operator()() const {
    if (!node.m_pNode)
      throw TypedBadConversion<T>(node.Mark());

    T t;
    if (convert<T>::decode(node, t)) // NOTE: THIS IS THE LINE THE COMPILER ERROR IS REFERENCING
      return t;
    throw TypedBadConversion<T>(node.Mark());
  }
};

有人知道我为什么会收到这个错误吗?

【问题讨论】:

  • 那么你只需要dereference每个item,这是一个pointer类型的Inventory,并将它传递给decode
  • @codekaizer 我不手动调用编码/解码,据我了解,这是 yaml-cpp 库调用的东西,所以我不知道我是否(或如何)能够做到那
  • 你试过ThorsSerializer 看起来会简单很多。您实际上不需要编写任何代码。 gist.github.com/Loki-Astari/0363c54fcd3db0a144e58e91ee6e0f01
  • 哎呀错过了指针的事情。你确定你需要那个吗?除非InventoryItem 是多态的,看起来有点矫枉过正。

标签: c++ pointers yaml yaml-cpp


【解决方案1】:

根据 gamedev.net 的回答,问题是我的解码需要如下所示:

static bool decode(const Node& node, InventoryItem* inventoryItem) {
  // @todo validation
  inventoryItem = new InventoryItem(); // NOTE: FIXES COMPILER ERROR
  inventoryItem->name = node["name"].as<std::string>();
  inventoryItem->baseValue = node["baseValue"].as<int>();
  inventoryItem->weight = node["weight"].as<float>();

  return true;
}

这是因为 yaml-cpp 库代码只是用T t; 声明了变量,在指针类型的情况下意味着它未初始化(对于正常值,它由默认构造函数初始化)。

【讨论】:

  • 这是内存泄漏。您永远不会删除在函数开始时分配的 InventoryItem,也不会在函数返回后引用指针来删除它。
猜你喜欢
  • 2015-12-06
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
相关资源
最近更新 更多