我遇到一个问题,我有一个配置文件,我用boost :: property_tree解析它:info_parser。
我使用此代码来完成工作:
struct _Config
{
std::string info[2];
boost::property_tree::ptree pt;
_Config()
{
//check if config file exists, if not create it, etc, do other stuff not related to the issue
//this code reproduces the issue
//DEFAULT VALUE, can be changed by configuration later
info[0] = "If updating this file make sure to update all settings accordingly.";
info[1] = "This program has been created by Name 'Nickname' Lastname";
}
void Save()
{
boost::property_tree::info_parser::write_info(".\\config.cfg", pt);
}
void Load()
{
boost::property_tree::info_parser::read_info(".\\config.cfg", pt);
{
//check if variable already exists in config file, if yes load it to
{
//try to load entry
boost::optional<std::string> v = pt.get_optional<std::string>("Info.a");
if (v.is_initialized())
//overwrite default value
info[0] = v.get();
}
//if entry does not exist it will be created now, else the loaded value will be saved
pt.put<std::string>("Info.a", info[0]);
}
//again for next variable
{
{
boost::optional<std::string> v = pt.get_optional<std::string>("Info.b");
if (v.is_initialized())
info[1] = v.get();
}
pt.put<std::string>("Info.b", info[1]);
}
Save();
}
~_Config()
{
Save();
pt.clear();
}
} Config;
现在,我的部分第一次看起来像这样:
Info
{
a "If updating this file make sure to update all settings accordingly."
b "This program has been created by Name 'Nickname' Lastname"
}
再次启动时,我的配置在保存时变为:
Info
{
a If updating this file make sure to update all settings accordingly.
b This program has been created by Name 'Nickname' Lastname
}
但重新启动代码后,信息部分变得一团糟,我的程序中断了:
Info
{
a If
updating this
file make
sure to
update all
accordingly. ""
b This
program has
been created
by Name
'Nickname' Lastname
}
如何确保空格是可接受的字符并且不删除引号?我还注意到我在配置文件中发表的任何评论都没有保存,是否有保存它们的选项?
我在32位应用程序中使用Windows 1.5 x64上的Visual Studio 2013的boost 1.55。
答案 0 :(得分:4)
这是Undefined Behaviour,具体是
这里的表现非常微妙!
Valgrind告诉我,info_parser::is_simple_data<char>
正在访问已释放的字符串。该字符串将是本地静态。两者都是从__run_exit_handlers()
调用的,但不是按任何特定顺序调用的!有关说明,请参阅链接的C ++ FAQ条目。
解决方案,不要依赖RAII的全球静力学:
int main()
{
_Config Config;
Config.Load();
}
很好,看到 Live On Coliru