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

Exception BadConversion when reading twice within a for loop of a container

Open julien-lecomte opened this issue 9 years ago • 2 comments

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.

julien-lecomte avatar Nov 21 '16 15:11 julien-lecomte