Returning QList with local scope variables



  • 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;
    }@



  • 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).


  • Moderators

    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.



  • That helped me, thank you both


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.