How to fix problems with owner of RapidXML String?

RapidXML is a fast, lightweight C ++ XML DOM Parser, but it has some quirks.

Worst of all, this is in my opinion:

3.2 String property.

The nodes and attributes created by RapidXml do not have their own names and values. They just keep pointers to them. This means that you must be careful when setting these values ​​manually using xml_base::name(const Ch *) or xml_base::value(const Ch *) .

It is necessary to ensure that the lifetime of the transmitted string is the least extended lifetime of the node / attribute. The easiest way to achieve this is to allocate a line from the memory_pool belonging to the document. using memory_pool::allocate_string() for this purpose.

Now I understand that this is done for speed, but it looks like a car accident awaiting its appearance. The following code looks harmless, but the "name" and "value" go beyond when foo returns, so the document is undefined.

 void foo() { char name[]="Name"; char value[]="Value"; doc.append_node(doc.allocate_node(node_element, name, value)); } 

The suggestion of using allocate_string() according to the manual works, but it's so easy to forget.

Has anyone “improved” RapidXML to avoid this problem?

+7
c ++ rapidxml
source share
1 answer

I do not use RapidXML, but maybe my approach may solve your problem.

I started using Xerces, but I found it difficult, in addition to other minor annoyances, so I switched to CPPDOM. When I made the transition, I decided to create a set of wrapper classes so that my code does not depend on a specific XML engine, and I could transfer it to another if necessary.

I created my own classes to represent the main DOM objects (node, document, etc.). These classes use the internal pimpl idiom to use CPPDOM objects. Since my node object contains the “real” node object (from CPPDOM), I can control anything so that properly distributing and freeing the lines will not be a problem there.

Since my code is for CPPDOM, I don’t think it would be very useful for you, but I can publish it if you want.

By the way, if you already have too much code that already uses RapidXML, you can reproduce its interfaces in your wrapper classes. I did not do this because the code that Xerces used was not so long and I would still have to rewrite it.

+1
source share

All Articles