所以我试图将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语句(此代码位于yhll-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());
}
};
有谁知道为什么我会收到此错误?
答案 0 :(得分:0)
根据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;
声明变量,在指针类型的情况下,它意味着它是未初始化的(对于普通值,它由默认构造函数初始化)。 p>