简体   繁体   中英

Qt, implicit shared object, what happens on delete?

//Case 1:
QImage* tImg = new QImage("Some Image Here");
painter->drawImage(x, y, *tImg );
...
delete tImg;

//Case 2:
QImage* tImg = new QImage("Some Image Here");
{
    QImage aImg(*tImg);
    painter->drawImage(x, y, aImg );
}
...
delete tImg;

QImage is implicitly shared, when something (like the aImg ) get a "shared copy" of the original data, what will happen if I delete the original data, will the aImg still preserve the data?

And what happens to case 1, will drawImage create a shared copy?

Implicit sharing in Qt follows the CoW (copy on write) paradigm - objects will implicitly share the same internal resource as long as it is not modified, if some of the copies attempts to modify the resource, it will be "detached" from the shared resource, copy it and apply the modifications to it.

When object lifetime ends, it decrements the reference counter for the shared resource, and if it is zero that means no other object uses it, so it is deleted. If the reference count is more than zero, the resource remains alive until there are objects, referencing it.

In case 1 the shared resource will be deleted, as there are no more objects referencing it.

In case 2 it will be deleted as well, because aImg will be out of scope by the time tImg is deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM