A.J
A.J

Reputation: 348

Set copy constructor as default does not work when inherited from QObject

I tried to set copy constructor as default, but compiler alert with "... attempting to reference a deleted function". What's wrong with my code?

class A : public QObject
{
    Q_OBJECT
public:
    const QString s1;
    ...
    const QString sn;
    const QDateTime t1;
    ...
    const QDateTime tn;


    A() = delete;
    A(const QString &s1, ...);
    A(const A&) = default;
    ~A() = default;

    float fun1();
    ...
    float funn();

private:
    QString m_s1;
    ...
};

Upvotes: 1

Views: 294

Answers (1)

kocica
kocica

Reputation: 6467

QObject Class description page says following:

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page. That means you are not supposed to copy QT objects, since QObject is non-copyable by design.

Which means QObject can't be copied and all its descendants can't be copied also.

But

You may convert your class to QVariant which uses a copy ctor

void *ptr = QMetaType::construct(x->type, copy);

Upvotes: 3

Related Questions