yaml-cpp
yaml-cpp copied to clipboard
Exception BadConversion when reading twice within a for loop of a container
I would expect the following code to work but on the second block yamp-cpp throws a BadConversion exception:
syslog:
facility: LOG_LOCAL4
#include <iostream>
#include <yaml-cpp/yaml.h>
using namespace std;
int main()
{
std::vector<const char*> list{ "syslog", "facility" };
auto root = YAML::LoadFile("myfile.yaml");
// the first one always works, for the vector (or initializer list, etc)
{
auto n = root;
for (auto e : list)
n = n[e];
auto str = n.as<string>();
cout << "str = " << str << endl;
}
{ // the second one always throws
auto n = root;
for (auto e : list)
n = n[e];
// the following throws BadConversion:
auto str = n.as<string>();
cout << "str = " << str << endl;
}
}
For the code above to work, it's necessary to Clone the root when assigning to n.