2012-05-14 58 views
0

使用Xerces C++我從下面的模式生成了典型的C++代碼。在對象序列化後,我得到訪問衝突。我通過代碼的方式逐步向下,直到一些std :: basic_string的模板插入代碼出現,並且它似乎正在發生。C++ xerces對象的序列化導致訪問衝突。

我可以進入生成的代碼中發生問題的位置。但它似乎是矯枉過正。我確定這是我的代碼的問題。

我的代碼如下。

#include <sstream> 
#include <iostream> 
#include "..\XMLObjects\SomeXML.hxx" 

void serializeObject(Object* mess, std::string& result); 
void create(); 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
create(); 
return 0; 
} 

void create() 
{ 
std::string result; 

objectType oType("Status"); 
std::auto_ptr<Object> obj(&Object(oType)); 

time_t seconds=time(NULL); 

Object::status_type s(seconds); 
obj->status().set(s); 
obj->status()->timeOfUpdate(); 
serializeObject(obj.get(), result); 

} 

void serializeObject(Object* mess, std::string& result) 
{ 

std::ostringstream buff; 
xml_schema::namespace_infomap nsm; 
nsm[""].name = ""; 
nsm[""].schema = "SomeXML.xsd"; 

try 
{ 
    Object_(buff, *mess, nsm, "UTF-8", xml_schema::flags::no_xml_declaration); 
} 
catch (const xml_schema::exception& e) 
{ 
    std::cout << e << std::endl; 
    return; 
} 
catch(std::exception& ex) 
{ 
    std::string info(" Caught the exception "); 
    info+=ex.what(); 

} 
catch(...) 
{ 
    std::string info(" Caught an exception "); 

} 

    result=buff.str().c_str(); 

} 

以下是我用來生成代碼的模式。

<?xml version="1.0" encoding="utf-8"?> 

<!--<schema xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.com/SomeXML">--> 

    <xsd:complexType name ="Status" > 
    <xsd:sequence> 
     <xsd:element name="timeOfUpdate" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1"/> 
    </xsd:sequence> 
    </xsd:complexType> 


    <xsd:simpleType name="objectType"> 
    <xsd:restriction base="xsd:string"> 
     <xsd:enumeration value="Status"/> 
     <xsd:enumeration value="Thing A"/> 
     <xsd:enumeration value="Thing B"/> 
    </xsd:restriction> 
    </xsd:simpleType> 

    <xsd:complexType name="Object" > 
    <xsd:sequence> 
    <xsd:element name="objectType" type ="objectType" minOccurs="1" maxOccurs="1" /> 
     <xsd:element name ="status" type ="Status" minOccurs="0" maxOccurs="1"/> 
    </xsd:sequence> 

    </xsd:complexType > 


    <xsd:element name="Object" type="Object" /> 
</xsd:schema> 

回答

2

std::auto_ptr<Object> obj(&Object(oType));

頭痛這是最有可能的一個來源。這看起來像你正在創建一個臨時的,然後把它的地址,並將其存儲在一個auto_ptr。

臨時性會立即超出範圍,您將留下一個懸掛指針。另外,當它到達示波器的結尾時,它會嘗試使用原來位於堆棧上的指針delete

嘗試用

std::auto_ptr<Object> obj(new Object(oType));

取代它,或者,如果您使用的是C++ 11兼容的編譯器,使用

std::unique_ptr<Object> obj(new Object(oType));

的auto_ptr以來在最新被棄用標準。

+0

這應該可以工作,但切換到std :: unique_ptr可能會很好。 std :: auto_ptr已被最新標準棄用。 – luke

+0

@luke:好點,我會提及的 –

+0

謝謝。這是一個愚蠢的錯誤,我使用參數中創建的引用而不是指針。 .c_str()忽略是原始代碼的保留。我爲此使用了QT字符串。可能仍然是一個更好的方式來做到這一點。 –