rapidxml添加属性的内存分配问题

来源:互联网 发布:单片机输出脉冲信号 编辑:程序博客网 时间:2024/05/04 05:15
 今天在用rapidxml生成xml的时候碰到了一个奇怪的问题
rapidxml::xml_node<>* srvnode = doc.allocate_node(rapidxml::node_element,iter->m_name.c_str(),"");srvnode->append_attribute(doc.allocate_attribute("ip",iter->m_ip.c_str()));srvnode->append_attribute(doc.allocate_attribute("ftpport",toString(iter->m_ftpport).c_str()));


生成的xml,其他地方都正常,就“ftpport”的属性总是显示乱码,开始以为是toString函数的问题,但是我换了一种转换方式后这个问题依然存在,同时我调试的时候看到的toString

的返回值也正常,最后和同时讨论后,他给我解释rapidxml的函数在创建新节点或者属性的时候,传入的参数要么是由内部分配器分配的内存要么应该指向一块短期内不会被释放的内存。

原来如此,于是我改了代码之后

rapidxml::xml_node<>* srvnode = doc.allocate_node(rapidxml::node_element,iter->m_name.c_str(),"");srvnode->append_attribute(doc.allocate_attribute("ip",iter->m_ip.c_str()));char* port = doc.allocate_string(toString(iter->m_ftpport).c_str());srvnode->append_attribute(doc.allocate_attribute("ftpport",port));

乱码的问题果然消失了,原来allocate_attribute方法创建一个属性的时候,attribute的m_value指针只是简单的指向了一块内存地址,在后期将doc写入文件,会将attribute转化为字符串,如果此时m_value指向的地址内存被释放的话,那么就会出现我先的问题了。所以我的解决方案就是用rapidxml自己的内存池分配一块内存,保存m_value指向的值,这样就OK了。

写在这里纯粹是做个记录,希望对某些同志也有帮助!

原创粉丝点击