[Qt-interest] How to deal with pointers for a QDataStream?
Oliver Heins
heins at sopos.org
Tue Apr 20 12:14:25 CEST 2010
Hi André,
Andre Somers <andre at familiesomers.nl> writes:
> On 19-4-2010 14:41, Oliver Heins wrote:
>> I have a data structure which holds some pointers:
>>
>> class Token
>> {
>> public:
>> enum Type { Space, Paragraph, Kern, Char, Format, Note, End };
>> enum SubType { Bold, Italic,
>> Header1, Header2, Header3, Header4, Header5, Header6,
>> Itemize, Enumerate, Description, Item,
>> Note1, Note2, Note3, Note4, Note5 };
>>
>> [...]
>>
>> Type type;
>> SubType subType;
>> QChar chr;
>> Token *parent;
>> QLinkedList<Token *> children;
>> Token *partner;
>> };
>>
>> As saving pointers directly to a QDataStream will obviously not work,
>> what would be a good strategy to save the structure?
>>
>>
>
> One way is to give each item you need to store a pointer to an ID that
> is unique for the file (if such a thing is not already there), and
> store these ID's instead of the pointers to the objects. On loading,
> you can reconstruct the pointers by using the ID's to lookup the
> addresses from some (temporary?) data structure such as a QHash<int,
> Token*> that you keep around at loading time.
Thanks, that's the way I intent to go. However, I run into another
problem: The data I write is not read properly.
This is how I go: I write my MagicNumber and the highest unique id to
the file. Then I traverse my QLinkedList<Token*>, writing the tokens:
while (i.hasNext())
out << *(i.next());
On reading, MagicNumber and the max id are set properly. Then I try to
read the data into a QVector<Token> tokenVec:
in >> tokenVec;
But the Tokens get filled with garbage. This is how the << and >>
operators are defined:
QDataStream &operator<<(QDataStream &out, const Token &token)
{
quint32 partner = token.partner ? token.partner->unique : 0;
quint32 parent = token.parent ? token.parent->unique : 0;
out << qint16(token.type) << qint16(token.subType) << token.chr
<< quint32(token.unique) << parent << partner;
return out;
}
QDataStream &operator>>(QDataStream &in, Token &token)
{
quint32 partner, parent;
qint16 type, subType;
token.parent = 0;
token.partner = 0;
in >> type >> subType >> token.chr >> token.unique >> parent >> partner;
token.type = static_cast<Token::Type>(type);
token.subType = static_cast<Token::SubType>(subType);
return in;
}
What is going wrong here?
TIA,
olli
--
Oliver Heins heins at sopos.org http://oliverheins.net/
http://blog.overheins.net/ F27A BA8C 1CFB B905 65A8
http://scriptorium-adp.de/ 2544 0F07 B675 9A00 D827
1024D/9A00D827 2004-09-24 -- gpg --recv-keys 0x9A00D827
Please avoid sending me Word or PowerPoint attachments:
http://www.gnu.org/philosophy/no-word-attachments.html
More information about the Qt-interest-old
mailing list