c++ - 试图了解 RapidXml 内存分配

标签 c++ xml pointers return-value rapidxml

我在 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 = ... 返回 *我的节点;

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

最佳答案

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

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

如果您需要一个 xml_node,您总是可以解除对指针的引用(首先检查 NULL)。不过,如果您以后真的想使用返回的节点及其子节点,最好只使用带有 -> 的返回指针并按值传递指针。

关于c++ - 试图了解 RapidXml 内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673110/

相关文章:

Java dom document.getElementsByTagName ("") 返回 null?

c++ - 如何从函数内部将函数指针传递给函数

c++ - 您将如何支持 libQtCassandra 库中的 super 列?

c++ - 从 C++ 程序执行 Applescript

java - 将 xml 解析为 java 对象时没有单字符串构造函数/工厂方法错误

c - 使用指针字符串会导致段错误

delphi - 如何解决Delphi错误: Incompatible types: 'PWideChar' and 'Pointer'

c++ - 从围绕 xyz 的旋转找到 xyz 方向

C++目录树数据转化为 vector

java - 如何使我的 TextView 宽度为其父级的一半?