开发者

Qt Should I derive from QDataStream?

开发者 https://www.devze.com 2022-12-22 12:40 出处:网络
I\'m currently using QDataStream to serialize my classes. I have quite a few number of my own classes that I serialize often. Should I derive QDataStream to create my own DataStream class? Or is there

I'm currently using QDataStream to serialize my classes. I have quite a few number of my own classes that I serialize often. Should I derive QDataStream to create my own DataStream class? Or is there a better pattern than this? Note that these custom classes are used by many of our projects, so maybe doing so will make coding easier.

Another way to phrase this question is: when a framework provides you with a serialization class, how do 开发者_Python百科you handle serializing your own custom-type classes such that you don't have to remember how to serialize them everytime (enhance usability) and also following best software-engineering practices (following patterns).


That would get out of control very quickly. A better approach is to define operator<< and operator>> between QDataStream and your class. Even cleaner might be to simply have serialization methods on your classes that read/write to a QDataStream (so that you would call for example, obj->serialize(myStream)).


The current way that I'm handling this is as follow:

Rather than deriving from QDataStream, I create a serializer class for each object I need to serialize.

For example, if I have:

class MyOwnClass

I would then create a class called:

class MyOwnClassSerializer
{
public:
  static QByteArray const serialize(MyOwnClass const&);
};

The reason why I didn't add a

QByteArray serialize() const;

to class MyOwnClass is so that people can use MyOwnClass without depending on Qt. Also not all MyOwnClass clients are interested in serializing the class.

Any comments would be appreciated! =)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号