Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Created December 29, 2022 09:09
Show Gist options
  • Save lixingcong/a750ab950ceb0b48be4e483c5cc209f2 to your computer and use it in GitHub Desktop.
Save lixingcong/a750ab950ceb0b48be4e483c5cc209f2 to your computer and use it in GitHub Desktop.
Qt implicitly shared class demo 隐式共享
#include "Employee.h"
#include <QString>
class EmployeeData : public QSharedData
{
public:
EmployeeData()
: id(-1)
{}
// 要在这个构造函数中赋值
EmployeeData(const EmployeeData& other)
: QSharedData(other)
, id(other.id)
, name(other.name)
{}
~EmployeeData() { qDebug("~EmployeeData %d", id); }
int id;
QString name;
};
Employee::Employee()
: d(new EmployeeData)
{
}
Employee::Employee(int id, const QString& name)
: d(new EmployeeData)
{
setId(id);
setName(name);
}
Employee::~Employee()
{
qDebug("~Employee()");
}
Employee::Employee(const Employee& other)
: d(other.d)
{}
Employee& Employee::operator=(const Employee& other)
{
d = other.d;
return *this;
}
void Employee::setId(int id)
{
d->id = id;
}
void Employee::setName(const QString &name)
{
d->name = name;
}
int Employee::id() const
{
return d->id;
}
QString Employee::name() const
{
return d->name;
}
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <QSharedDataPointer>
class QString;
// Demo from https://doc.qt.io/qt-6/qshareddatapointer.html
class EmployeeData;
class Employee
{
public:
Employee();
Employee(int id, const QString& name);
virtual ~Employee();
// Qt文档:若EmployeeData所有成员已经在本头文件中声明,
// 则无需实现拷贝构造函数和赋值构造函数
// 本例子由于隐藏了EmployeeData的实现,故要手动实现
Employee(const Employee& other);
Employee& operator=(const Employee&);
void setId(int id);
void setName(const QString& name);
int id() const;
QString name() const;
private:
QSharedDataPointer<EmployeeData> d;
};
#endif // EMPLOYEE_H
#include <QCoreApplication>
#include "Employee.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Q_UNUSED(app)
{
qDebug("\ntest operator=()");
Employee e1(100, "AAAA");
Employee e2(200, "BBBB");
e1 = e2;
}
{
qDebug("\ntest copy constructor()");
Employee e1(100, "AAAA");
Employee e2(e1);
Q_UNUSED(e2)
}
{
qDebug("\ntest e2.setId()");
Employee e1(100, "AAAA");
Employee e2(e1);
e2.setId(99999);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment