我正在尝试使用 get_child
从 boost::ptree
获取子树,如下所示:
我有:
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;
}
}
当我调用
ConfigFile cf("myfile.json");
ptree pt = cf.getSubTree("path.to.child")
返回后函数崩溃
terminate called after throwing an instance of 'std::length_error'
有人可以帮我解决这个问题吗?我做错了什么?
最佳答案
您正在返回对本地的引用。那行不通的。读这个:
Can a local variable's memory be accessed outside its scope?
修复:
ptree getSubTree(const string& path)
{
return pt.get_child(path);
}
您的结果是 Undefined Behaviour 的表现形式并且在不同的日子、编译器、运行时可能会有所不同......
关于c++ - Boost:如何从现有属性树中获取子树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22811483/