yaml-cpp icon indicating copy to clipboard operation
yaml-cpp copied to clipboard

Need explanation / improve tutorial

Open gelldur opened this issue 5 years ago • 4 comments
trafficstars

I just started using yaml-cpp and I did navigation from key like: "my.magic.str.value" to access nested values in YAML files.

I did this with code:

	YAML::Node node = _root;
	for(const auto& element : path)
	{
		node = node[element];
		if(!node)
		{
			return node;
		}
	}
	return node;

So thanks to that I could navigate through tree. It works fine for first execution then it stops as we modify _root ...

I found this question also: https://stackoverflow.com/questions/43597237/yaml-cpp-modifies-underlying-container-even-for-const-nodes

It would be nice to explain this in tutorial or forbid it somehow. Solution is to use recursion. E.g.

static YAML::Node goDeep(YAML::Node parent, unsigned level, const std::vector<std::string>& levels)
{
	if(level == levels.size())
	{
		return parent;
	}
	if(!parent)
	{
		return parent;
	}

	return goDeep(parent[levels.at(level)], level + 1, levels);
}

YAML::Node ConfigValue::find(const std::string& key) const
{
	const auto levels = gcpp::string::split(key, "."s);
	return goDeep(*_storage, 0, levels);
}

gelldur avatar Jul 25 '20 07:07 gelldur

I face the same issue in implementing the same behavior. It renders this library useless, especially since there are no compiler warnings despite marking my class member function const. A contract is broken.

SignalWhisperer avatar Aug 28 '20 20:08 SignalWhisperer

FYI Ive hit the same issue, I had to wrap YAML::Node in my own object to control for this behavior

robambalu avatar Nov 12 '20 19:11 robambalu

I have the same issue. The assignment semantics for Node makes no sense. Even if it acts as a pointer, accessing a copy should not modify original object. I guess I'll have to use libfyaml...

stilgarpl avatar Jan 21 '21 11:01 stilgarpl

Please, either open Wiki for editing or update tutorial. Thanks!

hinell avatar Jun 12 '23 08:06 hinell