使用C ++ 11创建隐式共享类的更简单方法?

时间:2015-05-29 10:09:53

标签: 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), 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;
};

Link

有没有办法摆脱这种基本的getter / setter方法,编写尽可能少的代码?

我想写一些类似于Rust的东西,它与Qt的隐式共享类(引用计数和东西)非常相似。

例如:

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
}

感谢。

0 个答案:

没有答案