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 ?
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)
精彩评论