-1

According to implicit sharing concept in following example we must experience low memory usage in Windows Task Manager.

We create 1000000 object in a for loop from Employee class and it might share its internal data (EmployeeData class) between created objects.

for (int i = 0; i < 1000000; ++i) {

    Employee *e1 = new Employee(); // calls default constructor
    Employee *e2 = e1; 
    Employee *e3 = e2;

    //e1->setName("Hans Holbein"); // ***
}

***: if uncomment mentioned line according to Qt documentation QSharedDataPointer it will be detaches from shared data and creates its own copy of EmployeeData.

EmployeeData and Employee class:

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, const 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(const QString &name) { d->name = name; }

    int id() const { return d->id; }
    QString name() const { return d->name; }

  private:
    QSharedDataPointer<EmployeeData> d;
};

Platform: Windows 10

Qt Version: 5.7

Compiler: MSVC 2015 32bit

The result is (from Task Manager):

  • Release: 40M RAM usage
  • Debug: 189M RAM usage

Question:

Based on provided loop assume EmployeeData size as 12 bytes, it must create one instance of EmployeeData and share it with another 999,999 object instances, and so memory usage must be reduced at least under 3M, is it Ok?

So if we uncomment the following line it must create 1000,000 unique instance of EmployeeData, so memory used by instances goes up, is that Ok?

//e1->setName("Hans Holbein");
4

1 回答 1

2

这里没有隐式共享,你只有两个指向同一个对象的指针。

隐式共享仅在使用对象的复制构造函数或赋值运算符时才有效。

忽略for循环中巨大的内存泄漏new,这样做将利用隐式共享

Employee *e2 = new Employee(e1); // copy constructor, implicit sharing
于 2016-09-15T16:44:31.963 回答