Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. General talk
  3. The Lounge
  4. Recurring C++ and Qt anti-patterns
Forum Update on Monday, May 27th 2025

Recurring C++ and Qt anti-patterns

Scheduled Pinned Locked Moved The Lounge
126 Posts 17 Posters 58.8k Views
  • 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.
  • fcarneyF Offline
    fcarneyF Offline
    fcarney
    wrote on last edited by
    #24

    @JonB said in Recurring C++ and Qt anti-patterns:

    one local variable to nullptr with just a mov instruction must be negligible, compared to whatever is involved in freeing memory, no?

    Correct. My math was wrong. It is 5 nanoseconds. At least for dereffed pointer, but timing was nearly the same for local variable as well.

    C++ is a perfectly valid school of magic.

    JonBJ 1 Reply Last reply
    3
    • fcarneyF fcarney

      @JonB said in Recurring C++ and Qt anti-patterns:

      one local variable to nullptr with just a mov instruction must be negligible, compared to whatever is involved in freeing memory, no?

      Correct. My math was wrong. It is 5 nanoseconds. At least for dereffed pointer, but timing was nearly the same for local variable as well.

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by
      #25

      @fcarney
      Ahhh, that would make much more sense! :)
      A nanosecond doesn't sound too long, I don't think I could get much done in it could I?

      1 Reply Last reply
      0
      • aha_1980A Offline
        aha_1980A Offline
        aha_1980
        Lifetime Qt Champion
        wrote on last edited by
        #26

        One more example for the hall of shame:

        QByteArray ba = "Hello World";
        QString s = QString::fromStdString(ba.toStdString());
        

        We have two problems here:

        1. The conversion to and from std::string is unneeded
        2. This only works for ASCII characters. QString::fromUtf8(ba); would most often be the correct choice, sometimes also QString::fromLocal8Bit(ba);

        Qt has to stay free or it will die.

        1 Reply Last reply
        4
        • aha_1980A Offline
          aha_1980A Offline
          aha_1980
          Lifetime Qt Champion
          wrote on last edited by
          #27

          One more note to string processing:

          QString empty = ""; is not the correct way to create an empty string, that is QString empty;

          To clear an non-empty QString data, use data.clear() instead data = "";.

          The same applies to QByteArrays.

          Qt has to stay free or it will die.

          1 Reply Last reply
          4
          • fcarneyF Offline
            fcarneyF Offline
            fcarney
            wrote on last edited by
            #28

            @aha_1980 said in Recurring C++ and Qt anti-patterns:

            QString empty = ""; is not the correct way to create an empty string, that is QString empty;
            To clear an non-empty QString data, use data.clear() instead data = "";

            Interesting... I did a couple of tests to see if it behaves the same way for comparisons. The only difference I can find between clear and setting to "" is the isNull test:

                qInfo() << "string test";
                QString empty;
                QString str = "";
                qInfo() << bool(empty == str);
                qInfo() << str.isNull();
                str.clear();
                qInfo() << bool(empty == str);
                qInfo() << str.isNull();
            

            output:

            string test
            true
            false
            true
            true
            

            If the string was set to "" is returns false for isNull. I have never had the occasion to use this test and am not sure what it is for. I guess it would be important if you want to determine if an empty string was assigned to the variable versus nothing being assigned.

            C++ is a perfectly valid school of magic.

            aha_1980A 1 Reply Last reply
            0
            • fcarneyF fcarney

              @aha_1980 said in Recurring C++ and Qt anti-patterns:

              QString empty = ""; is not the correct way to create an empty string, that is QString empty;
              To clear an non-empty QString data, use data.clear() instead data = "";

              Interesting... I did a couple of tests to see if it behaves the same way for comparisons. The only difference I can find between clear and setting to "" is the isNull test:

                  qInfo() << "string test";
                  QString empty;
                  QString str = "";
                  qInfo() << bool(empty == str);
                  qInfo() << str.isNull();
                  str.clear();
                  qInfo() << bool(empty == str);
                  qInfo() << str.isNull();
              

              output:

              string test
              true
              false
              true
              true
              

              If the string was set to "" is returns false for isNull. I have never had the occasion to use this test and am not sure what it is for. I guess it would be important if you want to determine if an empty string was assigned to the variable versus nothing being assigned.

              aha_1980A Offline
              aha_1980A Offline
              aha_1980
              Lifetime Qt Champion
              wrote on last edited by
              #29

              @fcarney I just think the isNull() method should be deprecated. Even the documentation states:

              Qt makes a distinction between null strings and empty strings for historical reasons. For most applications, what matters is whether or not a string contains any data, and this can be determined using the isEmpty() function.

              Qt has to stay free or it will die.

              1 Reply Last reply
              1
              • fcarneyF fcarney

                Okay, I am just confusing myself. If you delete a pointer you must immediately set it to null. Otherwise you risk double delete, which is bad. But its okay to delete something set to null. Got it.

                Edit:
                Why doesn't delete set the pointer to null then? That seems like it may be an antipattern in and of itself.

                Christian EhrlicherC Online
                Christian EhrlicherC Online
                Christian Ehrlicher
                Lifetime Qt Champion
                wrote on last edited by Christian Ehrlicher
                #30

                @fcarney said in Recurring C++ and Qt anti-patterns:

                Why doesn't delete set the pointer to null then?

                Because the operator delete is defined to take a pointer, not a reference to a pointer.
                https://en.cppreference.com/w/cpp/memory/new/operator_delete

                Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                Visit the Qt Academy at https://academy.qt.io/catalog

                1 Reply Last reply
                3
                • fcarneyF Offline
                  fcarneyF Offline
                  fcarney
                  wrote on last edited by fcarney
                  #31

                  Welcome to another edition of Is this an Anti-Pattern?

                  Harmless looking pattern 1:

                  std::vector<int64_t> list = {9,9,9,9,9,9,9,9,9,9};
                  int64_t sum = std::accumulate(list.begin(), list.end(), 0);
                  

                  Harmless looking pattern 2:

                  std::vector<int64_t> list = {9,9,9,9,9,9,9,9,9,9};
                  int64_t prod = std::accumulate(list.begin(), list.end(), 1, std::multiplies<int64_t>());
                  

                  Lack of understanding pattern 3:

                  std::set<int> list = {9,8,7,6};
                  int last = *(list.end()--);
                  

                  Lack of understanding pattern 4:

                  std:vector<int> list = {9,8,7,6};
                  int last = *(list.end()--);
                  

                  I still don't get why this cannot be done for sets and vectors...
                  Okay, was using post decrement instead of a prefix decrement. DOH!

                  int last = *(--list.end());
                  

                  Logic fudgery pattern 5 (this is more an optical illusion, it was to me anyway):

                  bool is_leap_year(int year){
                      return (year % 4 == 0) && (year % 100 == 0) ? (year % 400 == 0) : true;
                  }
                  

                  C++ is a perfectly valid school of magic.

                  1 Reply Last reply
                  0
                  • sierdzioS Offline
                    sierdzioS Offline
                    sierdzio
                    Moderators
                    wrote on last edited by
                    #32

                    Small things from me:

                    • lack of const in signal declarations. A signal will never modify an object so it can always be const. Qt will const_cast it away anyway, but it enables you to emit signals from const methods and (possibly) compiler to optimize a bit more
                    • overuse of lambdas in slot connections even when a normal slot just makes more sense

                    (Z(:^

                    A 1 Reply Last reply
                    4
                    • sierdzioS sierdzio

                      Small things from me:

                      • lack of const in signal declarations. A signal will never modify an object so it can always be const. Qt will const_cast it away anyway, but it enables you to emit signals from const methods and (possibly) compiler to optimize a bit more
                      • overuse of lambdas in slot connections even when a normal slot just makes more sense
                      A Offline
                      A Offline
                      Asperamanca
                      wrote on last edited by
                      #33

                      @sierdzio said in Recurring C++ and Qt anti-patterns:

                      Small things from me:

                      • lack of const in signal declarations. A signal will never modify an object so it can always be const. Qt will const_cast it away anyway, but it enables you to emit signals from const methods and (possibly) compiler to optimize a bit more
                      • overuse of lambdas in slot connections even when a normal slot just makes more sense

                      This brings me to a philosophical question: Do I want to be able to emit a signal from a const method, although the slot(s) attached to the signal may well modify data the originating const method could not itself modify?

                      sierdzioS 1 Reply Last reply
                      0
                      • A Asperamanca

                        @sierdzio said in Recurring C++ and Qt anti-patterns:

                        Small things from me:

                        • lack of const in signal declarations. A signal will never modify an object so it can always be const. Qt will const_cast it away anyway, but it enables you to emit signals from const methods and (possibly) compiler to optimize a bit more
                        • overuse of lambdas in slot connections even when a normal slot just makes more sense

                        This brings me to a philosophical question: Do I want to be able to emit a signal from a const method, although the slot(s) attached to the signal may well modify data the originating const method could not itself modify?

                        sierdzioS Offline
                        sierdzioS Offline
                        sierdzio
                        Moderators
                        wrote on last edited by
                        #34

                        @Asperamanca said in Recurring C++ and Qt anti-patterns:

                        This brings me to a philosophical question: Do I want to be able to emit a signal from a const method, although the slot(s) attached to the signal may well modify data the originating const method could not itself modify?

                        Yes, it's very debatable :D I did find a few occasions where it was useful (latest example: modifying behaviour of QTreeView without patching Qt - I have emitted a signal from const overloaded method and did my modifications there), but I agree it does not feel "right".

                        (Z(:^

                        Kent-DorfmanK 1 Reply Last reply
                        0
                        • fcarneyF Offline
                          fcarneyF Offline
                          fcarney
                          wrote on last edited by fcarney
                          #35

                          Given the code:
                          modules.h

                          #ifndef MODULES_H
                          #define MODULES_H
                          
                          #include <string>
                          
                          void reg_module(int type, std::string name, int initedValue);
                          
                          #endif // MODULES_H
                          

                          modules.cpp

                          #include "modules.h"
                          
                          using namespace std;
                          
                          struct Modules
                          {
                              Modules(): m_initedValue(0){}
                              int m_type;
                              string m_name;
                              int m_initedValue;
                          } global_modules_struct[128];
                          
                          void reg_module(int type, std::string name, int initedValue){
                              global_modules_struct[type].m_type = type;
                              global_modules_struct[type].m_name = name;
                              global_modules_struct[type].m_initedValue = initedValue;
                          }
                          

                          moduletype.h

                          #ifndef MODULETYPE_H
                          #define MODULETYPE_H
                          
                          // nothing here
                          
                          #endif // MODULETYPE_H
                          

                          moduletype.cpp

                          #include "moduletype.h"
                          #include "modules.h"
                          
                          struct SomeModule{
                              SomeModule(){
                                  reg_module(10, "some type", 5);
                              }
                          } SomeModuleInstance;
                          

                          Ignore obvious indexing bounds checking issues for the array itself. Also ignore external array indexing possibly being out of bounds.

                          I just ran into a form of this problem in our code and it did not exhibit issues in Linux (that we know of) and did show issues in Windows. Linux used gcc and Windows used mingw. Same version of Qt 5.12.2 etc. Once identified it was really easy to see why this is a big issue.

                          Edit:
                          Technically global_modules_struct is not really global either. So ignore the misleading name.

                          C++ is a perfectly valid school of magic.

                          1 Reply Last reply
                          0
                          • Chris KawaC Offline
                            Chris KawaC Offline
                            Chris Kawa
                            Lifetime Qt Champion
                            wrote on last edited by Chris Kawa
                            #36

                            I had to dig through this thing once, only the real code was like a hundred times longer and more convoluted.

                            // Library.h statically linked to and included in DLL and EXE
                            struct SomeType
                            {
                               int typeId();
                            };
                            Q_DECLARE_METATYPE(SomeType);
                            
                            // Library.cpp
                            int SomeType::typeId()
                            {
                                return qMetaTypeId<SomeType>();
                            }
                            
                            // main app
                            SomeType& var1 = getItFromDLL();
                            SomeType& var2 = getItFromEXE();
                            
                            bool same = var1.typeId() == var2.typeId(); // nope
                            

                            Pretty ugly thing to debug, especially since once in blue moon it actually works :/

                            kshegunovK 1 Reply Last reply
                            2
                            • B Offline
                              B Offline
                              Brunner2
                              Banned
                              wrote on last edited by
                              #37
                              This post is deleted!
                              1 Reply Last reply
                              0
                              • sierdzioS sierdzio

                                @Asperamanca said in Recurring C++ and Qt anti-patterns:

                                This brings me to a philosophical question: Do I want to be able to emit a signal from a const method, although the slot(s) attached to the signal may well modify data the originating const method could not itself modify?

                                Yes, it's very debatable :D I did find a few occasions where it was useful (latest example: modifying behaviour of QTreeView without patching Qt - I have emitted a signal from const overloaded method and did my modifications there), but I agree it does not feel "right".

                                Kent-DorfmanK Offline
                                Kent-DorfmanK Offline
                                Kent-Dorfman
                                wrote on last edited by
                                #38

                                @sierdzio said in Recurring C++ and Qt anti-patterns:

                                Yes, it's very debatable :D I did find a few occasions where it was useful (latest example: modifying behaviour of QTreeView without patching Qt - I have emitted a signal from const overloaded method and did my modifications there), but I agree it does not feel "right".

                                Actually, I have zero problem with this. The way my mind works it makes perfect sense, as the signal is a message to a receiving class (any class). It's not the sender method that modifies the object state. It is the message. My mind differentiates between the two.

                                1 Reply Last reply
                                0
                                • fcarneyF fcarney

                                  @aha_1980
                                  Apparently the standard allows for it:
                                  https://stackoverflow.com/questions/704466/why-doesnt-delete-set-the-pointer-to-null

                                  The creator himself wonders why it isn't so. Its like C++ is this beautiful, amazing, and now, WILD animal roaming free in cyberspace... Yeah, maybe the analogy isn't all that great, but it does conjure up a cool picture.

                                  Kent-DorfmanK Offline
                                  Kent-DorfmanK Offline
                                  Kent-Dorfman
                                  wrote on last edited by
                                  #39

                                  @fcarney said in Recurring C++ and Qt anti-patterns:

                                  Apparently the standard allows for it:
                                  https://stackoverflow.com/questions/704466/why-doesnt-delete-set-the-pointer-to-null
                                  The creator himself wonders why it isn't so. Its like C++ is this beautiful, amazing, and now, WILD animal roaming free in cyberspace... Yeah, maybe the analogy isn't all that great, but it does conjure up a cool picture.

                                  Jumping back a few months on this one, but I think the decision to leave alone the pointer value upon an object delete is solid. If I understand the standard properly, the target of a delete can be an lvalue or and rvalue. So delete 0x34fc3d2200 should be a valid operation, right? How ya gonna change the value of an rvalue (in a traditional sense)?

                                  1 Reply Last reply
                                  0
                                  • Chris KawaC Offline
                                    Chris KawaC Offline
                                    Chris Kawa
                                    Lifetime Qt Champion
                                    wrote on last edited by Chris Kawa
                                    #40

                                    Imagine clearing some sort of array:

                                    for(type* ptr = some_array; something ; ++ptr)
                                    {
                                         delete ptr;
                                    }
                                    

                                    Now imagine delete would zero that pointer. Do you see the problem? You would have to make another, temporary, pointer just so you zero the copy and your original doesn't get changed. In other words you're paying for what you don't use or even want. There's also problem of const pointers or pointers that you got from external APIs that do their own bookkeeping and might actually need that pointer value even after delete. It would create more problems than it solves.

                                    1 Reply Last reply
                                    5
                                    • fcarneyF Offline
                                      fcarneyF Offline
                                      fcarney
                                      wrote on last edited by
                                      #41
                                              int 🥩=1;
                                              int 🧀=1;
                                              int 🥬=1;
                                              int 🍞=1;
                                              int 🍅=1;
                                              int 🥪=🥩+🥬+🍅+🧀+🥩;
                                              cout << 🥪 << endl;
                                      

                                      Fails to compile in C++17...

                                      C++ is a perfectly valid school of magic.

                                      1 Reply Last reply
                                      1
                                      • Kent-DorfmanK Offline
                                        Kent-DorfmanK Offline
                                        Kent-Dorfman
                                        wrote on last edited by
                                        #42

                                        @fcarney said in Recurring C++ and Qt anti-patterns:

                                            int 🥩=1;
                                            int 🧀=1;
                                            int 🥬=1;
                                            int 🍞=1;
                                            int 🍅=1;
                                            int 🥪=🥩+🥬+🍅+🧀+🥩;
                                            cout << 🥪 << endl;
                                        

                                        Fails to compile in C++17...

                                        What's this "int" stuff? Doesn't the 17 standard deduce the type based on the rvalue? Not that I think that is necessarily a good thing though.

                                        fcarneyF 1 Reply Last reply
                                        0
                                        • Kent-DorfmanK Kent-Dorfman

                                          @fcarney said in Recurring C++ and Qt anti-patterns:

                                              int 🥩=1;
                                              int 🧀=1;
                                              int 🥬=1;
                                              int 🍞=1;
                                              int 🍅=1;
                                              int 🥪=🥩+🥬+🍅+🧀+🥩;
                                              cout << 🥪 << endl;
                                          

                                          Fails to compile in C++17...

                                          What's this "int" stuff? Doesn't the 17 standard deduce the type based on the rvalue? Not that I think that is necessarily a good thing though.

                                          fcarneyF Offline
                                          fcarneyF Offline
                                          fcarney
                                          wrote on last edited by
                                          #43

                                          @kent-dorfman said in Recurring C++ and Qt anti-patterns:

                                          🍞

                                          The real problem is this variable is unused.

                                          C++ is a perfectly valid school of magic.

                                          1 Reply Last reply
                                          1

                                          • Login

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