C++ 使用C++;11?
下面是类似Qt的隐式共享/COW类的最小示例:C++ 使用C++;11?,c++,qt,C++,Qt,下面是类似Qt的隐式共享/COW类的最小示例: #include <QSharedData> #include <QString> class EmployeeData : public QSharedData { public: EmployeeData() : id(-1) { } EmployeeData(const EmployeeData &other) : QSharedData(other), id(other.id
#include <QSharedData>
#include <QString>
class EmployeeData : public QSharedData
{
public:
EmployeeData() : id(-1) { }
EmployeeData(const EmployeeData &other)
: QSharedData(other), id(other.id), name(other.name) { }
~EmployeeData() { }
int id;
QString name;
};
class Employee
{
public:
Employee() { d = new EmployeeData; }
Employee(int id, QString name) {
d = new EmployeeData;
setId(id);
setName(name);
}
Employee(const Employee &other)
: d (other.d)
{
}
void setId(int id) { d->id = id; }
void setName(QString name) { d->name = name; }
int id() const { return d->id; }
QString name() const { return d->name; }
private:
QSharedDataPointer<EmployeeData> d;
};
谢谢。“摆脱这种基本的getter/setter方法”,它与Qt的隐式共享无关,只是基本的API设计。如果您真的愿意,您可以将Qt的隐式共享机制包装在一个
ComplexStruct
实例周围,并在一个getter/setter对中公开整个结构。
struct A {
ComplexStruct complexValue; // some struct which has lost of data
}
struct B {
A value;
int count;
}
int main() {
B b;
A a = b.value; // here I get deep copy of struct A with ComplexStruct, which is slow,
// but with Qt-like implicitly sharing it will be fast and easy
}