When parsing YAML file using yaml-cpp, does it 'copy' all child nodes?

843 views Asked by At

When parsing yaml file, normally we get root node from parser.

And I'm wondering if I can reference the root node after parsing process. Like below.

YAML::Node* globalRoot;

void ParseDocument(filename)
{
  YAML::Parser parser(fin)
  parser.GetNextDocument(*globalRoot);
}

void myFunction()
{
  ParseDocument("myYAML.yml");

  // After the method above, we lose the parser instance since it's a local variable.
  // But if all child data is copied, below code should be safe.
  // If globalRoot is just pointing inside the parser, this could be dangerous.

  std::string stringKey;
  (*globalRoot)["myKey"] >> stringKey;
}

Can I use like code above??

1

There are 1 answers

1
Jesse Beder On BEST ANSWER

Yes, it does - once a Node is parsed, it does not rely on any memory from the Parser.

That said, in your example, you never actually construct the node pointed to by globalRoot. You'd need to call

globalRoot = new YAML::Node;

and even better, keep it in a smart pointer like std::auto_ptr.