Boost logo

Boost Users :

Subject: [Boost-users] How to use the optional with property_tree‏
From: 王郁槐 (wyhfly_at_[hidden])
Date: 2013-12-19 06:34:19


Could anyone help? Why the below code will crash on the below line? I'm using the boost property_tree. Thanks.

child1.get().put(sub_field, strValue);

=========================================================
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/any.hpp>
#include <boost/optional.hpp>

void writeConfig(const std::string &field, const std::string &sub_field, const std::string & strValue)
{
if (!boost::filesystem::exists(prog_cfg_file))
{
std::ofstream ofIniConfig(prog_cfg_file, std::ofstream::out|std::ofstream::app);
ofIniConfig.close();
}

boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(prog_cfg_file, pt);
boost::optional<boost::property_tree::ptree&> child1 = pt.get_child_optional(field);

if (child1)
{
boost::optional<boost::property_tree::ptree&> child2 = child1.get().get_child_optional(sub_field);

if (child2)
{
child2.get().put_value(strValue);
}else
{
child2.get().put_value(strValue);
}
}else
{
child1.get().put(sub_field, strValue);
}

boost::property_tree::ini_parser::write_ini(prog_cfg_file, pt);
}

int main()
{
writeConfig("test", "a", "OK");
return 0;
}

--
兰生幽谷, 不以无人而不芳...



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net