Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. [SOLVED] Get all Objects with same class ?
Forum Updated to NodeBB v4.3 + New Features

[SOLVED] Get all Objects with same class ?

Scheduled Pinned Locked Moved General and Desktop
37 Posts 4 Posters 13.4k Views 1 Watching
  • 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.
  • D Offline
    D Offline
    deleted28
    wrote on 31 Jan 2015, 12:43 last edited by
    #1

    Hello,

    my application creates several objects of the same CustoClass in different parts of code.
    If all necessary Objects are created i need access to each of this objects.

    How can i get a list of all existing objects with the same CustomClass in the entire application ?
    (Or do i need to add to a list myself alwayswhen creating a new object )

    Maybe "QMetaObject" is a a candidate but i do not know how to.

    thnaks wally

    1 Reply Last reply
    0
    • G Offline
      G Offline
      gyll
      wrote on 31 Jan 2015, 12:52 last edited by
      #2

      why on earth would you rely on something which is not C++ (qmetaobjects etc)? just add in the class itself a static list, and in the object constuctor and destructor add/remove the objects you are creating/deleting

      @
      // custom.h
      #include <vector>
      class Custom {
      public:
      Custom();
      ~Custom();
      static std::vector<class Custom*> instances;
      ...
      }

      // custom.cpp
      #include "custom.h"
      std::vector<class Custom*> Custom::instances; // need to instantiate this because 'instances' is static
      Custom::Custom() {
      instances.push_back(this);
      ...
      }

      Custom::~Custom() {
      assert(instances.size());
      instances.pop_back();
      ...
      }
      @

      Once you have the above, you have access to 'instances' anywhere in your program (provided you #include "custom.h" in the cpp files where you use 'instances') via name qualification: Custom::instances

      1 Reply Last reply
      0
      • D Offline
        D Offline
        deleted28
        wrote on 31 Jan 2015, 13:19 last edited by
        #3

        I do not know what exactly i can do with "QMetaObject",
        I'm even suprised its not C++.
        "QMetaObject":http://doc.qt.io/qt-5/qmetaobject.html#details
        "The QMetaObject class contains meta-information about Qt objects."

        Anyway, your suggestion seems to be an answer to the :
        (Or do i need to add to a list myself always when creating a new object )
        thank you very much!

        Now i need to get behind this lines:

        static std::vector<class Custom*> instances;
        ? create a static vector of (my customclass) type CustomClass ?
        and
        assert(instances.size());
        ? no idea yet ?

        Independent on my first idea QMetaObject may do this job,
        is there no way to get a list of objects of the same class in another way
        without the instances vector in class ?

        wally

        1 Reply Last reply
        0
        • G Offline
          G Offline
          gyll
          wrote on 31 Jan 2015, 13:45 last edited by
          #4

          there is no native C++ construct that allows you to access all instances of a class in a program

          of course you can create the 'instances' list outside the class

          the 'assert' statement is just a precaution to check that indeed when you delete an item from the list the list was not empty. again, it's just a precaution.

          as for static members, it's simply a member of the class which is shared by all the instances of the class, and because it is not allocated for each instance it has to be instantiated explicitly (usually the most convenient place is in the cpp file of the class). if you're not familiar with static members you should either just build a separate list, or read about static members and play around with them a little to get used with them (they are pretty powerful stuff imo, so getting used with them might well be worth it)

          PS
          i forgot to put 'public' in my class declaration, corrected that now.

          1 Reply Last reply
          0
          • D Offline
            D Offline
            deleted28
            wrote on 31 Jan 2015, 14:21 last edited by
            #5

            thanks for explanation !
            Yes, playing around with this is necessary :)
            My CustomClass named : "KNhead"

            got error in knhead.cpp: here line 12
            error: undefined reference to `KNhead::instances'
            knhead.h
            @#include <QObject>
            #include <QByteArray>
            #include <assert.h>

            class KNhead
            {

            private:

            // QByteArray *intern_qba;

            public:
            KNhead();
            ~KNhead();

            static std::vector<class KNhead*> instances;
            
            QByteArray *intern_qba;
            

            ...
            @

            knhead.cpp
            @#include "knhead.h"
            #include <QDebug>

            // need to instantiate this because 'instances' is static
            std::vector<class KNhead*> instances;

            KNhead::KNhead()
            {
            intern_qba = new QByteArray("Hokuspokus");
            qDebug() << intern_qba->size();

            instances.push_back(this);       // <<<<<<<<<<<<
            

            }

            KNhead::~KNhead()
            {
            // assert(instances.size());
            // instances.pop_back();

            }@

            Maybe you see the problem immediately :)

            1 Reply Last reply
            0
            • G Offline
              G Offline
              gyll
              wrote on 31 Jan 2015, 14:45 last edited by
              #6

              oops, right, sorry, the line in the cpp file:
              @std::vector<class KNhead*> instances;
              @
              should be
              @std::vector<class KNhead*> KNhead::instances;
              @
              i.e. the instantiation should be KNhead::instances. i corrected it in the listing.

              PS
              And of course the 'custom.h' should #include <vector> and 'custom.cpp' should #include "custom.h", added these to the listing

              1 Reply Last reply
              0
              • D Offline
                D Offline
                deleted28
                wrote on 31 Jan 2015, 15:13 last edited by
                #7

                great, that was also my first suspect

                As you see, i do not have experience witht Qt and C++,
                but i have to create a swarm of objects and let them communicate
                with the other using several rules. (maybe similar to neuronal net)
                Goal is to observe mofification of this net depending on communication rules.

                still a long way to go :)

                1 Reply Last reply
                0
                • G Offline
                  G Offline
                  gyll
                  wrote on 31 Jan 2015, 15:24 last edited by
                  #8

                  oh yeah
                  RULE OF THUMB: DO NOT USE ANYTHING SPECIFIC TO Qt whenever you don't REALLY need to, or else you'll get an app that requires Qt, and you just never know with these open source guys, today they're here, tomorrow they're all gone. Just use plain C++, no QByteArray, no signal/slots, etc, except when you really need them, and even then TRY TO CREATE YOUR OWN CLASSES AND FUNCTIONS AS WRAPPERS over what t provides so that you can easily change the framework if you'll have to

                  1 Reply Last reply
                  0
                  • JKSHJ Offline
                    JKSHJ Offline
                    JKSH
                    Moderators
                    wrote on 31 Jan 2015, 17:27 last edited by
                    #9

                    Hi,

                    [quote author="wally123" date="1422710389"]I do not know what exactly i can do with "QMetaObject"[/quote]The documentation that you linked to says that QMetaObject is "not normally required for application programming, but it is useful if you write meta-applications, such as scripting engines or GUI builders." -- you usually won't need to use it for regular programs, but it provides advanced conveniences if you ever need them.

                    However, QMetaObject does not give you the ability to track all instances of your custom class. You will need to implement your own tracker, like gyll said.

                    [quote author="wally123" date="1422710389"]I'm even suprised its not C++.[/quote]I believe gyll meant that the meta-object system is not "plain C++". QMetaObject itself is fully implemented in C++, and can be used like any other C++ class that you might create in your applications.

                    [quote author="wally123" date="1422714070"]
                    @
                    std::vector<class KNhead*> instances;

                    KNhead::KNhead()
                    {
                    instances.push_back(this);
                    }

                    KNhead::~KNhead()
                    {
                    instances.pop_back();
                    }
                    @
                    [/quote]This approach only works if you to always delete the objects in reverse order of their creation. Imagine this scenario:

                    You create 3 objects ('A', 'B', and 'C'). They are added to your vector in this order ('A' is first, 'C' is last). If you then delete object 'B', its destructor calls pop_back(), which removes 'C' from the vector!

                    I suggest using an unordered set instead of a vector, and removing a specific object instead of the last object.

                    @
                    QSet<KNhead*> instances;

                    KNhead::KNhead()
                    {
                    instances.insert(this);
                    }

                    KNhead::~KNhead()
                    {
                    instances.remove(this);
                    }
                    @

                    Or, if you want to stick to the STL:
                    @
                    std::unordered_set<KNhead*> instances;

                    KNhead::KNhead()
                    {
                    instances.insert(this);
                    }

                    KNhead::~KNhead()
                    {
                    instances.erase(find(this));
                    }
                    @

                    [quote author="gyll" date="1422717891"]you just never know with these open source guys, today they're here, tomorrow they're all gone.[/quote]Qt has been around for 20 years, it is backed by a commercial company, and it is spreading. I highly doubt Qt will be gone in the foreseeable future.

                    [quote author="gyll" date="1422717891"]TRY TO CREATE YOUR OWN CLASSES AND FUNCTIONS AS WRAPPERS over what t provides so that you can easily change the framework if you'll have to[/quote]That sounds like a lot of extra work. Is it worth the effort? How often have you changed the framework of an established app?

                    Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                    1 Reply Last reply
                    0
                    • D Offline
                      D Offline
                      deleted28
                      wrote on 31 Jan 2015, 19:43 last edited by
                      #10

                      this is really great, thanks a lot both :)

                      1 Reply Last reply
                      0
                      • SGaistS Offline
                        SGaistS Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on 31 Jan 2015, 20:15 last edited by
                        #11

                        Hi,

                        To add to the excellent points of JKSH, you also have the "KDE free Qt foundation":https://www.kde.org/community/whatiskde/kdefreeqtfoundation.php who's purpose is to secure the availability of Qt

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        1 Reply Last reply
                        0
                        • D Offline
                          D Offline
                          deleted28
                          wrote on 31 Jan 2015, 20:28 last edited by
                          #12

                          as for KDE, right ?
                          but the STL also gives a cool fealing

                          1 Reply Last reply
                          0
                          • G Offline
                            G Offline
                            gyll
                            wrote on 31 Jan 2015, 21:09 last edited by
                            #13

                            JKSH: "I suggest using an unordered set instead of a vector, and removing a specific object instead of the last object."

                            OUCH, that's correct, my code is TOTALLY WRONG. you have to remove the object that you are deleting, not just the last object.

                            so here we go, correction:
                            @
                            // custom.h
                            #include <unordered_set>
                            class Custom {
                            public:
                            Custom();
                            ~Custom();
                            static std::unordered_set<Custom*> instances;
                            }

                            // custom.cpp
                            #include "custom.h"
                            #include <assert.h>
                            std::unordered_set<Custom*> Custom::instances;

                            Custom::Custom() {
                            instances.insert(this);
                            ...
                            }

                            Custom::~Custom() {
                            assert(instances.count(this));
                            instances.erase(this);
                            ...
                            }
                            @

                            PS
                            unordered_set is C++11, so if you're using gcc you have to add to your .pro file (the Qt project file) a line like this (at least for now, until gcc parses C++11 by default):
                            @
                            QMAKE_CXXFLAGS += -std=c++11
                            @

                            you can safely make the line above the first line in your .pro file

                            If you're using some other compiler (MSVC, llvm, whatever) then you might have to check the compiler's documentation for enabling C++11 support (i'm not sure about this, maybe QMAKE takes care of the translation, dunno)

                            1 Reply Last reply
                            0
                            • SGaistS Offline
                              SGaistS Offline
                              SGaist
                              Lifetime Qt Champion
                              wrote on 31 Jan 2015, 23:30 last edited by
                              #14

                              As for every user of the Qt library

                              STL is a different beast

                              @CONFIG += c++11@

                              sets everything needed to use C++11

                              Interested in AI ? www.idiap.ch
                              Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                              1 Reply Last reply
                              0
                              • D Offline
                                D Offline
                                deleted28
                                wrote on 1 Feb 2015, 08:24 last edited by
                                #15

                                I'm sorry but i need more help.
                                I do not know how to work on the QSet instances.

                                knhead.h:
                                @#include <QObject>
                                #include <QSet>

                                class KNhead
                                {
                                public:
                                KNhead();
                                ~KNhead();

                                QSet<KNhead*> instances;
                                

                                };@

                                knhead.cpp:
                                @#include "knhead.h"

                                QSet<KNhead*> instances;

                                KNhead::KNhead()
                                {
                                instances.insert(this);
                                }

                                KNhead::~KNhead()
                                {
                                instances.remove(this);
                                }@

                                main.cpp:

                                @#include <QCoreApplication>
                                #include <QDebug>
                                #include <QSet>
                                #include "knhead.h"

                                int main(int argc, char *argv[])
                                {
                                QCoreApplication a(argc, argv);
                                qDebug() << "Hello\n";

                                KNhead *cell_1 = new KNhead;
                                KNhead *cell_2 = new KNhead;
                                KNhead *cell_3 = new KNhead;
                                

                                // qDebug() << ??? instances.count() ??? ;

                                qDebug() << cell_1->instances.count();
                                qDebug() << cell_1->instances.size();
                                
                                qDebug() << cell_2->instances.count();
                                qDebug() << cell_2->instances.size();
                                
                                return a.exec(&#41;;
                                

                                }@

                                output:
                                @Hello

                                1
                                1
                                1
                                1
                                @

                                Is there a "static" missing ?
                                or do i need ust some more coffe to wake up this morning

                                1 Reply Last reply
                                0
                                • JKSHJ Offline
                                  JKSHJ Offline
                                  JKSH
                                  Moderators
                                  wrote on 1 Feb 2015, 08:33 last edited by
                                  #16

                                  [quote author="wally123" date="1422779095"]Is there a "static" missing ?[/quote]Yes, your set needs to be a static variable. You want all the different KNhead instances to write to the same set, after all.

                                  Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                                  1 Reply Last reply
                                  0
                                  • D Offline
                                    D Offline
                                    deleted28
                                    wrote on 1 Feb 2015, 08:51 last edited by
                                    #17

                                    just put a "static" in knhead.h line 10 and knhead.cpp line 3
                                    @
                                    static QSet<KNhead*> instances;
                                    @

                                    results in:

                                    error: undefined reference to `KNhead::instances'

                                    1 Reply Last reply
                                    0
                                    • JKSHJ Offline
                                      JKSHJ Offline
                                      JKSH
                                      Moderators
                                      wrote on 1 Feb 2015, 09:01 last edited by
                                      #18

                                      You need to define static member variables in a .cpp file somewhere. Add this line to knhead.cpp (outside of any functions):

                                      @
                                      QSet<KNhead*> KNhead::instances;
                                      @

                                      Do some extra reading to understand "how to use static member variabless":http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

                                      Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                                      1 Reply Last reply
                                      0
                                      • D Offline
                                        D Offline
                                        deleted28
                                        wrote on 1 Feb 2015, 09:09 last edited by
                                        #19

                                        Ok, now no errors and it s output looks good:
                                        @Hello

                                        3
                                        3
                                        3
                                        3@

                                        Do i need always an arbitrary instance of class KNhead to access instances
                                        or is there another way ?

                                        e.g. qDebug() << cell_1->instances.count();
                                        or cell_2 or cell_3

                                        1 Reply Last reply
                                        0
                                        • G Offline
                                          G Offline
                                          gyll
                                          wrote on 1 Feb 2015, 09:38 last edited by
                                          #20

                                          As i told you in my first reply (you forgot :P):
                                          "Once you have the above, you have access to ‘instances’ anywhere in your program (provided you #include “custom.h” in the cpp files where you use ‘instances’) via name qualification: 'Custom::instances'

                                          So, in any cpp file where you want to access 'instances' just make sure to #include "knhead.h" and then just use 'KNhead::instances':
                                          @
                                          #include "knhead.h"
                                          ...
                                          qDebug() << KNhead::instances.count();
                                          ...
                                          @

                                          1 Reply Last reply
                                          0

                                          1/37

                                          31 Jan 2015, 12:43

                                          • Login

                                          • Login or register to search.
                                          1 out of 37
                                          • First post
                                            1/37
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved