Can a class deriving from QSharedData use the default copy constructor?

  • In the example in Qt docs, a copy constructor is explicitly defined for a trivial class with only copyable members.

    Is this intentional? Or is it fine to declare the copy constructor as "=default"?

  • As long as the QSharedData copy constructor is called (which should be guaranteed by the standard) =default works just as well

  • In the example, Employee and EmployeeData are defined in the same header file. But now imagine you split the two parts and you have:


    #ifndef EMPLOYEE_H
    #define EMPLOYEE_H
    #include <QString>
    #include <QSharedDataPointer>
    class EmployeeData;
    class Employee
        Employee(int id, const QString &name);
        Employee(const Employee &other);
        int id() const;
        void setId(int id);
        QString name() const;
        void setName(const QString &name);
        QSharedDataPointer<EmployeeData> d;
    #endif // EMPLOYEE_H

    Now the compiler couldn't generate the copy constructor as the member QSharedDataPointer<EmployeeData> d is not fully known. So in this case, the usual case I'd say, you actually have to define / implement the (trivial) copy-constructor.

  • I think we are talking about two different things.
    Did you mean to =default the copy constructor for EmployeeData or the one for Employee?

  • Oh. If you were talking about EmployeeData, yes, you can reduce that code to:

    struct EmployeeData : public QSharedData
        int id = -1;
        QString name;

  • Yes, I was talking about the private data class. Since all I was doing was faithfully copy every single member, "=default" deemed a viable alternative.

    I have tried it and so far have not run into any issues. Together with your input, I feel confident this is safe to do so, and the example looks as it does just because it was written pre-C++11


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.