Can I use QSharedData when inheriting from QObject?

How to hide private implementation (implicit sharing) in Qt:

I have Employee.cpp the following in the 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 the private part, say Employee.cpp, I get: error: invalid use of incomplete type 'struct EmployeeData p>

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

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

So, can I use QSharedData when inheriting from QObject?

+4
source share
1 answer

So, can I use QSharedData when inheriting from QObject?

You cannot inherit QObject when using QSharedData. QSharedData uses copy-on-write semantics and detach () is called to create a copy of the data when it will no longer be shared. To make a copy, you need a copy constructor that QObject does not support.

pimpl (or handle-body / opaque -pointer idiom) often gives the data class a link to a public implementation, namely how you expect to work with signals and slots.

QSharedDataPointer provides most of the implementation details, but it is also very instructive to look at the pimpl idiom used in Qt ( see Q_D and friends )

+2
source

Source: https://habr.com/ru/post/1306398/


All Articles