7

I am trying to get a subtree from a boost::ptree using get_child like this:

I have:

class ConfigFile
{
  ptree pt;
  ConfigFile(const string& name)
  {
    read_json(name, pt);
  }
  ptree& getSubTree(const string& path)
  {
    ptree spt = pt.get_child(path);
    return spt;
  }
}

and when I call

ConfigFile cf("myfile.json");
ptree pt = cf.getSubTree("path.to.child")

the function crashes after return saying

terminate called after throwing an instance of 'std::length_error'

Can someone help me with this? what am I doing wrong?

sehe
  • 374,641
  • 47
  • 450
  • 633
thedarkside ofthemoon
  • 2,251
  • 6
  • 31
  • 48

1 Answers1

7

You're returning a reference to local. That won't work. Read this:

Can a local variable's memory be accessed outside its scope?

Fix:

ptree getSubTree(const string& path)
{
     return pt.get_child(path);
}

Your result was a manifestition of Undefined Behaviour and could be different on different days, compilers, runs...

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Thanks, I have found another way [here](http://www.informit.com/articles/article.aspx?p=25033&seqNum=3) by creating a pointer on the stack, but your solution is better. – thedarkside ofthemoon Apr 02 '14 at 13:04
  • That "pointer on the stack" article is old, and predates C++11. Sehe's answer allows efficient move semantics, which are new to C++11. – MSalters Apr 08 '19 at 12:19