Implicit vs Explicit Sharing

來源:互聯網
上載者:User
Implicit vs Explicit Sharing

Implicit sharing might not be right for the Employee class. Consider a simple example that creates two instances of the implicitly sharedEmployee class.

 #include "employee.h" int main() {     Employee e1(1001, "Albrecht Durer");     Employee e2 = e1;     e1.setName("Hans Holbein"); }

After the second employee e2 is created and e1 is assigned to it, both e1 and e2 refer to Albrecht Durer, employee 1001. BothEmployee objects point to the same instance of EmployeeData, which has reference count 2. Then e1.setName("Hans Holbein") is called to change the employee name, but because the reference count is greater than 1, a copy on write is performed before the name is changed. Now e1 and e2 point to different EmployeeData objects. They have different names, but both have ID 1001, which is probably not what you want. You can, of course, just continue with e1.setId(1002), if you really mean to create a second, unique employee, but if you only want to change the employee's name everywhere, consider using explicit sharing in the Employee class instead of implicit sharing.

If you declare the d pointer in the Employee class to be QExplicitlySharedDataPointer<EmployeeData>, then explicit sharing is used and copy on write operations are not performed automatically (i.e. detach() is not called in non-const functions). In that case, aftere1.setName("Hans Holbein"), the employee's name has been changed, but both e1 and e2 still refer to the same instance ofEmployeeData, so there is only one employee with ID 1001.

In the member function documentation, d pointer always refers to the internal pointer to the shared data object.

 

http://qt-project.org/wiki/ValueBasedAndPointerBasedTypes

 

What we would like is a data type that looks like a value based type(顯示共用)

  1. QWebElement e1 = webPage->getElementByName("company_info"); // e1 appears as a value based type

  2. QWebElement e2 = e1; // can be copied. e1 and e2 are one and the same.

  3. e2.setAttribute(attrib, value); // any change in e2 reflects in e1 (unlike implicitly shared data types)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.