简体   繁体   中英

Weird result with rapidXml in C++ append_node

I have this class:

// XmlWrapper.h
class XmlWrapper{
private:
    xml_document<> doc;
public:
    XmlWrapper();
    string addNode( string node_name);
            string getXmlString();
};

// XmlWrapper.cpp
XmlWrapper::XmlWrapper(){};

XmlWrapper::addNode(string node_name){
    char _name[name.size()+1];
    strcpy(_name,name.c_str());
    _name[name.size()] = '\0';
    xml_node<> *root = doc.allocate_node(node_element,_name);
    this->doc.append_node(root);
    delete root;
    return SUCCESS;
}

string XmlWrapper::getXmlString(){
    string xmlString;
    print(back_inserter(xmlString), this->doc, 0);
    return xmlString;
}

And this is my main.cpp:

XmlWrapper wrapper;
wrapper.addNode("message");
cout << wrapper.getXmlString() << endl;

However, my result is a list of weird thing!! if i cout wrapper.getXmlString() in addNode function, the result will be okie! So what's is my problem?

Edited: if i use directly in main.cpp like this below,every thing is go right:

xml_document<> doc;
xml_node<> *message_node = doc.allocate_node(node_element, "message");
doc.append_node(message_node);
string buffer;
print(back_inserter(buffer),doc,0);
cout << buffer << endl;

Why this thing happen?

What dirkgently said - _name is on the stack, and will be destroyed when you get out of the scope of the function. You can use allocate_string, or write your own garbage collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM