为什么 const YAML::Node 对象的行为不像 yaml-cpp 中的类似值的对象?



我正在尝试用yaml-cpp创建一个YamlConfig类。它的主要功能之一是,在 Minecaft API Bukkit 的风格中,其用户可以通过像"map1.map2.map3.keyoffinalvalue"这样的字符串轻松地引用地图树中的不同节点(例如,包含包含地图但深度不同的地图的地图(。我在下面的最小示例中编写了 seek 函数来做到这一点,但即使它被标记为 const,每次调用时打印出来的字符串也是不同的,似乎只是包含上次调用的最终值的映射。这表明m_rootNode似乎正在改变的问题。这是怎么回事?

最初,这个函数不是 const (调试后我需要让它成为 non-const(,我认为由于可怕的 API 设计,YAML::Node充当某种引用,而不是像C++标准那样行为良好的类似值的类型(令人惊讶的是 API 的用户通常是可怕的 API 设计(。但是,这与标记为 const 的函数不一致。因此,我现在不知道发生了什么。我也试图通过我的搜索引擎找到类似的问题,但除了成为同一个 YAML 库的一部分之外,没有出现任何远程相关的东西。

#include <yaml-cpp/yaml.h>
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
class YamlConfig{
public:
YamlConfig(const std::string &yaml);
YAML::Node seek(std::string_view key, bool create) const;
private:
YAML::Node m_rootNode;
static std::vector<std::string> split(std::string_view input, char delimeter);
};
YamlConfig::YamlConfig(const std::string &yaml){
m_rootNode = YAML::Load(yaml);
}
YAML::Node YamlConfig::seek(std::string_view key, bool create) const {
auto splitKey = split(key, '.');
YAML::Node current = m_rootNode;
YAML::Emitter emitter;
emitter << current;
std::cout << emitter.c_str() << std::endl;
for(const auto &keySegment : splitKey){
if(current.IsMap()){
current = current[keySegment];
if( (!current) && (!create) ){
throw std::runtime_error("Invalid YAML key due to attempting to descend in to non-existent node: " + keySegment);
}
}else{
throw std::runtime_error("Invalid YAML key due to attempting to descend in to non-map node: " + std::string(key));
}
}
return current;
}
std::vector<std::string> YamlConfig::split(std::string_view input, char delimeter) {
std::vector<std::string> output;
auto baseit = input.begin();
for(auto it=input.begin();it!=input.end();++it){
if(*it == delimeter){
output.emplace_back(baseit, it);
baseit = it+1;
if(*baseit == delimeter){
throw std::invalid_argument("Double delimiter found in string "" + std::string(input) + """);
}
}
}
output.emplace_back(baseit, input.end());
return output;
}
int main(){
const std::string yaml = "engine:n    view-distance: 16n    fullscreen: falsen";
std::cout << yaml << std::endl;
YamlConfig yamlConfig(yaml);
std::cout << yamlConfig.seek("engine.view-distance", false).as<std::string>() << std::endl;
std::cout << yamlConfig.seek("engine.view-distance", false).as<std::string>() << std::endl;
return 0;
}

编译后,此代码将生成以下输出,而无需我的注释:

engine: //this is the printout of the string in main
view-distance: 16
fullscreen: false
engine: //this is the first printout of the root node, good
view-distance: 16
fullscreen: false
16 //this is the printout of the value that was retrieved from the yaml data
view-distance: 16 //This is the second printout of the "root" node. It looks like the root node is now the engine node, changed via a const function What is going on? 
fullscreen: false
terminate called after throwing an instance of 'std::runtime_error' //this is an artifact of the root node seemingly changing, and is consistent with it changing to be the engine node
what():  Invalid YAML key due to attempting to descend in to non-existent node: engine
Aborted (core dumped)

编译命令:clang++ --std=c++17 -lyaml-cpp yaml.cpp -o yaml

快速浏览一下 API 就会发现以下几行:

mutable detail::shared_memory_holder m_pMemory;
mutable detail::node* m_pNode;

mutable修饰符告诉我们,即使是此节点上的const函数也可能更改这些值。这令人担忧,但实际上不是问题所在。如我们所见,YAML::Node只是对实际节点的引用。进一步挖掘,我们找到了赋值运算符的实现:

inline Node& Node::operator=(const Node& rhs) {
if (is(rhs))
return *this;
AssignNode(rhs);
return *this;
}
/* snip */
inline void Node::AssignNode(const Node& rhs) {
if (!m_isValid)
throw InvalidNode(m_invalidKey);
rhs.EnsureNodeExists();
if (!m_pNode) {
m_pNode = rhs.m_pNode;
m_pMemory = rhs.m_pMemory;
return;
}
m_pNode->set_ref(*rhs.m_pNode);
m_pMemory->merge(*rhs.m_pMemory);
m_pNode = rhs.m_pNode;
}

因此,正如我们所看到的,分配一个YAML::Node修改引用的节点,这是您的问题。即使您的函数const,这也有效,因为您仍然可以从 const 指针修改引用的数据。

问题是,应该如何使用 API?我真的不知道。operator[]返回值,而不是引用,因此不能使用指针;并且没有find函数会返回可以使用的迭代器。

答,诚然,可怕的解决方法是:

auto tmp = current[keySegment]; // get next node
current.~Node(); // destruct node reference (not the referenced node)
new (&current) Node(tmp); // call copy constructor with placement new to assign 
// tmp to current. necessary since current is invalid at this point.

或者,您可以递归地实现seek以避免重新分配current

最新更新