Implicit vs Explicit Sharing

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值