Hi,

You can access child2 only, if the child2 is true, otherwise you have no child2. An optional returns false if there is no value inside, then it is like a NULL pointer.

Merry Christmas!

On 19.12.2013 15:28, 王郁槐 wrote:
I still don't understand,could you please figure it out?thanks.


发送自魅族手机

-------- 原始邮件 --------
发件人:Olivier Tristan <o.tristan@uvi.net>
时间:周四 12月19日 22:08
收件人:boost-users@lists.boost.org
主题:Re: [Boost-users] How to use the optional with property_tree‏

Those following lines from your code should give you a hint

if (child2)
{
child2.get().put_value(strValue);
}
else
{
child2.get().put_value(strValue);
}



Le 19/12/2013 12:34, 王郁槐 a écrit :
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 mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users
-- 
Olivier TRISTAN
uvi.net

_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users


_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users