Question

How do I hide the private implementation (implicit sharing) in Qt:

I have Employee.cpp the following in my Employee.h header:

#include <QSharedData>
#include <QString>


class EmployeeData;
class Employee: public QObject
{
    Q_OBJECT
    public:
    Employee();
    Employee(int id, QString name);
    Employee(const Employee &other);
    void setId(int id);
    void setName(QString name);

    int id();
    QString name();

private:
    QSharedDataPointer<EmployeeData> d;
};

class EmployeeData : public QSharedData
{
  public:
    EmployeeData() : id(-1) { name.clear(); }
    EmployeeData(const EmployeeData &other)
        : QSharedData(other), id(other.id), name(other.name) { }
    ~EmployeeData() { }

    int id;
    QString name;
};

But when I move EmployeeData to a private part, say Employee.cpp I get: error: invalid use of incomplete type ‘struct EmployeeData’

However, if I change my definition to this it works fine:

class Employee
{
public:
    Employee();
    Employee(int id, QString name);
 ..

Thus, can I use QSharedData while inheriting from QObject ?

Was it helpful?

Solution

Thus, can I use QSharedData while inheriting from QObject ?

You cannot inherit from QObject when using QSharedData. QSharedData uses copy-on-write semantics and will call detach() to create a copy of the data when it's no longer being shared. In order to do the copy, a copy-constructor is needed, which QObject does not support.

The pimpl (or handle-body/opaque-pointer idiom) will often give the data class a reference to the public implementation, which is how you're expected to work with signals and slots.

QSharedDataPointer provides most of the implementation details, but it's also quite instructive to take a look at the pimpl idiom as used in Qt (see Q_D and friends)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top