YAML-CPP 编码/解码指针?



所以我正在尝试将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());
}
};

有谁知道为什么我可能会收到此错误?

根据 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;声明变量,在指针类型的情况下,这意味着它是未初始化的(对于普通值,它由默认构造函数初始化(。

最新更新