[Qt-interest] Implicitly Shared Classes
Scott Aron Bloom
Scott.Bloom at sabgroup.com
Sun Feb 15 19:04:38 CET 2009
> -----Original Message-----
> From: qt-interest-bounces at trolltech.com [mailto:qt-interest-
> bounces at trolltech.com] On Behalf Of Tom Browder
> Sent: 2009-02-15 05:04
> To: qt-interest at trolltech.com
> Subject: [Qt-interest] Implicitly Shared Classes
>
> I have a question about the efficiency of passing an implicitly shared
> class around. Consider function foo which returns a map apparently
> generated on the stack versus function foo2 in which the caller
> provides an existing map.
>
> QMap<int> M foo() {
> QMap<int> m;
> // ... put a lot of integers in m
> return m;
> }
>
> void foo2(QMap<int>& M) {
> // ... put a lot of integers in M
> }
>
> int main(int argc, char** argv) {
> QMap<int> M = foo; // 1. is m copied from m in foo as it goes out
> of scope?
> QMap<int> M2;
> foo2(M2); // 2. is this more efficient than 1?
> }
>
> In situation 1 is data copied from m in foo as it goes out of scope or
> does M just take over the data?
>
> Are both situations then equally efficient?
>
> Thanks.
>
> -Tom
[Scott Aron Bloom]
Its actually very well described throughout the QT docs (look at
http://doc.trolltech.com/4.4/shared.html), and they do a much much
better job at describing it then I could...
However, in general, when using implicitly shared, your case 1, passes
back a "wrapper class" of a shared pointer with a reference of 1. Then
the copy constructor is called, and a new wrapper class is created, but
the shared pointer is copied (not a deep copy) and the reference count
is increased to 2, when the call to foo exits and m is destroyed, the
reference count is decreased back to 1. Since no write was requested to
the shared pointed while its reference was > 1, no copying of the data
was done.
In the second case, the object M2 is passed via reference to foo2, no
copying of the internals is done, the actual data worked on, and then
the function is returned...
It works quite well, and memory copying is minimized..
That said, I can come up with a pro's and cons for both usage models,
that have more to do with code clarity, and API structure then
efficiency, since in the QT world, luckily that is removed from my
concern (for THIS issue... :) not all :) )
However, when I have taught advanced data structure classes, I usually
teach usage 2 in general, since many of the public data structures DON'T
do implicit sharing, and the assumption is that its MUCH MUCH slower to
do a deep copy even if the code isn't as easy follow.
Hope this helps...
Scott
More information about the Qt-interest-old
mailing list