c++ - 从类的成员函数返回指针

标签 c++ libxml2

我的代码看起来像这样:

xmlparser.h 文件:

#include <libxml++/libxml++.h>  
#include <iostream>
using namspace std, xmlpp;

class xmlpar {  
    public:
         xmlparse(){}
         ~xmlparse(){}
         const Node* root_node();
};

xmlparser.cc 文件:

#include "xmlparser.h"
const Node* xmlpar::root_node() {
    const Node* rnode;
    DomParser parser;
    parser.parse_file("sample.xml");
    if (parser) {
       rnode = parser.get->document()->get_root_node();
       cout << rnode->get_name(); // prints "component" as in xml file
       return rnode;
    }
 }

我的 main.cc 文件:

#include "xmlparser.h"
int main() {
    xmlparser par;
    const Node* root = par.root_node();
    cout << root->get_name(); // prints "PQ". --> Problem location
}

我首先编译了 xmlparser.cc 文件,然后编译了 main.cc,然后使用 main.o 和 xmlparser.o 创建了一个可执行文件。我在编译期间没有收到任何错误,但就像代码中一样,如果我从 root_node() 方法返回 rnode,则根的值 更改为“PQ”而不是“组件”。谁能告诉我这里发生了什么以及解决方案。

最佳答案

我不知道libxml2,但看起来您返回了指向本地对象的指针。

DomParser parser;

const Node* xmlpar::root_node() 中是本地对象。然后你就做你该做的事,最后

rnode = parser.get->document()->get_root_node();

这使得rnode指向文档中的某个位置。您返回指向它的指针,但在函数结束后(返回后),解析器将被销毁,因为它是本地对象。

这使得返回的指针无效,并且您有未定义的行为

关于c++ - 从类的成员函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7977278/

相关文章:

c++ - 如何将模板类的名称传递给模板参数?

ios - 找不到用于测试的libxml/tree.h文件

c - xmlParseFile 与 xmlReadFile (libxml2)

c++ - QT OpenSource,5.12.1,默认安装不产生 qtmainid.lib

c++ - _sleep() 函数不工作

c++ - 调用 weakref 传递的 Python 函数

libxml2 - 找不到 libxml2 和 iOS 5.0 SDK/Xcode 4.2 (beta 3) 的头文件

ruby - WindowsXP 上用于 Ruby 的 Nokogiri : 6 hours of my life gone

python - DTD 验证失败(Python)

c++ - 指向某物的指针,无法理解是什么类型