我的代码看起来像这样:
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/