Returning QList with local scope variables
-
wrote on 13 Mar 2012, 14:52 last edited by
Hi!
In doSmth() I create 2 objects of class Foo, and they will be destroyed as soon as doSmth() have excecuted. If I add f1 and f2 to QList, why they still can be accessed through QList<Foo> b = doSmth(); how it comes, if f1 and f2 are not copied when appended to QList, that I still can access them through result of doSmth ? (AFAIK, QList<T> stores pointers to type T)@
class Foo
{
...
};QList<Foo> doSmth()
{
Foo f1,f2;
QList<Foo> list;
list.append(f1);
list.append(f2);
return list;
}@ -
wrote on 13 Mar 2012, 15:07 last edited by
Hi,
The way you coded it, QList stores objects of type Foo, which means it creates objects on the heap and c0opies the contents. QList ALWAYS stores a copy of the data you put in (as all other containers also do).
-
wrote on 13 Mar 2012, 15:08 last edited by
As I understand it, (generally speaking - there are subtleties when storing pointer-sized data, etc. - the QList docs go into more detail) while QList internally uses a list of pointers to store (and implicitly share) data, it uses a copy of any data stored on the list.
So while your f1 and f2 are only scoped locally, a copy of them gets appended to the list, and those copies are implicitly shared with the returned QList.
-
wrote on 13 Mar 2012, 16:10 last edited by
That helped me, thank you both
2/4