提升:如何从现有属性树中获取子树?

the*_*oon 6 c++ boost boost-propertytree

我试图从这样的boost::ptree使用中得到一个子树get_child:

我有:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

当我打电话的时候

ConfigFile cf("myfile.json");
ptree pt = cf.getSubTree("path.to.child")
Run Code Online (Sandbox Code Playgroud)

函数在返回后崩溃了

terminate called after throwing an instance of 'std::length_error'
Run Code Online (Sandbox Code Playgroud)

有人可以帮我弄这个吗?我究竟做错了什么?

seh*_*ehe 6

您将返回对本地的引用.那不行.读这个:

可以在其范围之外访问局部变量的内存吗?

固定:

ptree getSubTree(const string& path)
{
     return pt.get_child(path);
}
Run Code Online (Sandbox Code Playgroud)

您的结果是未定义行为的表现,可能在不同的日子,编译器,运行中有所不同......