0

我在 C++ 程序中使用 RapidXml。好吧,没问题,它可以工作。我只是不明白为什么我必须使用指针而不是变量值...如果您查看 RapidXml wiki 页面,提供了一些示例,这是 RapidXml 开发人员提供的示例:

#include <iostream>
#include <string>
#include "rapidxml-1.13/rapidxml.hpp"
#include "rapidxml-1.13/rapidxml_print.hpp"
int main(int argc, char** argv);
int main(int argc, char** argv) {
    using namespace rapidxml;
    xml_document<> doc;
    // xml declaration
    xml_node<>* decl = doc.allocate_node(node_declaration);
    decl->append_attribute(doc.allocate_attribute("version", "1.0"));
    decl->append_attribute(doc.allocate_attribute("encoding", "utf-8"));
    doc.append_node(decl);
    // root node
    xml_node<>* root = doc.allocate_node(node_element, "rootnode");
    root->append_attribute(doc.allocate_attribute("version", "1.0"));
    root->append_attribute(doc.allocate_attribute("type", "example"));
    doc.append_node(root);
    // child node
    xml_node<>* child = doc.allocate_node(node_element, "childnode");
    root->append_node(child);
    xml_node<>* child2 = doc.allocate_node(node_element, "childnode");
    root->append_node(child2);
    std::string xml_as_string;
    // watch for name collisions here, print() is a very common function name!
    print(std::back_inserter(xml_as_string), doc);
    std::cout << xml_as_string << std::endl;
    // xml_as_string now contains the XML in string form, indented
    // (in all its angle bracket glory)
    std::string xml_no_indent;
    // print_no_indenting is the only flag that print() knows about
    print(std::back_inserter(xml_no_indent), doc, print_no_indenting);
    // xml_no_indent now contains non-indented XML
    std::cout << xml_no_indent << std::endl;
}

好吧,为什么它使用指向 xml_node 的指针???

我问这个是因为我需要一个函数来返回一个 xml_node ...

所以如果我这样做:

xml_node<>* mynode = ... return *mynode;

可以吗??因为我想稍后使用返回的节点及其所有子节点。这样做好不好?如果没有,我该怎么办?

4

3 回答 3

3

返回指针可能是为了避免调用节点的复制构造函数。只返回一个指针会更快,特别是考虑到节点可能已经在内部某个地方分配了。

他们也可以返回一个引用,但他们可能希望保留在无效调用上返回 NULL 的能力。

如果你需要一个 xml_node,你总是可以取消引用指针(首先检查 NULL)。但是,如果您以后真的想使用返回的节点及其子节点,最好将返回的指针与 -> 一起使用并按值传递指针。

于 2011-01-12T19:44:12.203 回答
2

好吧,为什么它使用指向 xml_node 的指针

可能是因为返回指向节点的指针比在返回时复制要快。

于 2011-01-12T19:33:27.723 回答
-2

好的......好吧,RapidXML 和许多其他类似 Xerces 的东西不返回值,而是返回指针,因此程序员无法获取值并一直复制......这样做是为了保留内存......

尤其是说到 DOM 的时候,对于 SAX 来说也差不多,这些解析器需要在程序运行的计算机 RAM 中创建一个非常复杂的内存分配结构。为了提供性能等所有构造函数和复制构造函数都是私有的。

看看图书馆......你会发现这个好技巧啊。

好吧,原因是我报告的原因,每个人都建议我。

我猜想当使用 c、c++ 和低级语言时,编程方式并不是那么直接……程序员不能很容易地获取节点并传递它或返回函数和类。

于 2011-01-12T20:00:06.517 回答