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?
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...