我遇到一个问题,我有一个配置文件,我用 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
}
如何确保空格是可接受的字符并且不会删除引号?我还注意到我在配置文件中所做的任何评论都没有保存,是否有保存它们的选项?
我在 Windows 8 x64 的 32 位应用程序中将 boost 1.55 与 Visual Studio 2013 结合使用。
最佳答案
它是 Undefined Behaviour ,特别是
static initialization fiasco
这里的表现相当微妙!
Valgrind 告诉我 info_parser::is_simple_data<char>
正在访问释放的字符串。该字符串将是本地静态。两者都是从 __run_exit_handlers()
调用的但没有任何特定的顺序!有关解释,请参阅链接的 C++FAQ 条目。
解决方案,不要依赖 RAII 的全局静态:
int main()
{
_Config Config;
Config.Load();
}
就好了,看看吧 Live On Coliru
关于c++ - boost::property_tree::info_parser 在值的空格处中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23681439/