Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    Returning QList with local scope variables

    General and Desktop
    3
    4
    3554
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • B
      bright day 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;
      }@

      1 Reply Last reply Reply Quote 0
      • G
        giesbert 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).

        Nokia Certified Qt Specialist.
        Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

        1 Reply Last reply Reply Quote 0
        • M
          mlong 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.

          Software Engineer
          My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

          1 Reply Last reply Reply Quote 0
          • B
            bright day last edited by

            That helped me, thank you both

            1 Reply Last reply Reply Quote 0
            • First post
              Last post