c++ - Boost:如何从现有属性树中获取子树?

标签 c++ boost boost-propertytree

我正在尝试使用 get_childboost::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/

相关文章:

c++ - boost::graph同构的使用

c++ - boost::chrono::time_point<> 和 boost::chrono::steady_clock::time_point 之间的区别

c++ - boost 属性树 : How to delete the specified parameters of the node

c++ - 使用 boost ptree 将 std::list 序列化为 json

c++ - 指示 Qi 转换属性失败的正确方法是什么?

被析构函数阻止的 C++ 异常处理

c++ - 编译器可以报告未知属性的错误吗?即使有范围?

c++ - 你用 VIM/Emacs/Terminals 开发 C/C++ 吗?这个实用的项目是什么?

c++ - 在一种方法中使用两个 boost 互斥体?

c++ - 来自 boost ptree 的 XML 版本和编码