开发者

Implementing implicitly shared classes outside of Qt

I'm familiar with the way Qt uses D-pointers for managing data. How do I do this in my code?

I tried this method:

1) move all data into a struct 2) add a QAtomicInt to the struct 3) implement a = operator and change my constructor/deconstructor to check-up on the reference count.

The is开发者_JS百科sue is, when I go to do a shallow copy of the object, I get an error about QObject declaring = as private. How then do I accomplish this?

Here's an example of my copy operator:

HttpRequest & HttpRequest::operator=(const HttpRequest &other)
{
    other.d->ref.ref();
    if (!d->ref.deref())
        delete d;
    d = other.d;
    return *this;
}

Am I going about this the wrong way?


AFAIK QObjects are not meant to be copied around. That's why QObject has a private operator= so the question is, why do you want to declare one and if you do, does your object indeeds needs to be a QObject?


The Object Model page on the documentation has a section called "Identity vs Value".

It reminds of the different things that an object might have established at runtime, and which are not intrinsic qualities at compile time (like dynamic properties, but also connections of signals and slots to other objects). And in the end, reminds:

For these reasons, Qt Objects should be treated as identities, not as values. Identities are cloned, not copied or assigned, and cloning an identity is a more complex operation than copying or assigning a value. Therefore, QObject and all subclasses of QObject (direct or indirect) have their copy constructor and assignment operator disabled.

So no, you should not attempt to create implicit sharing in classes derived from QObject, not only because it will fail, but because it is likely a design mistake. There are ways to serialize/deserialize a QObject tree, but normally is when you are using objects for their properties, to be exposed to QML, for example. Also, note that Q_GADGET can be an alternative to not inherit from QObject and still have properties (and hence be able to be copied).

That said, if your class doesn't derive from QObject, you can use QSharedData and QSharedDataPointer. Those classes are meant exactly for the very purpose of creating your own implicitly shared classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜