Boost: How to get a subtree form an existing property tree?
Asked Answered
P

1

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?

Phenology answered 2/4, 2014 at 12:27 Comment(0)
F
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...

Fleurette answered 2/4, 2014 at 12:42 Comment(2)
Thanks, I have found another way here by creating a pointer on the stack, but your solution is better.Phenology
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.Verbality

© 2022 - 2024 — McMap. All rights reserved.