Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-141134

Minimize plain new(): make_parented<QObject>

XMLWordPrintable

    • Icon: Suggestion Suggestion
    • Resolution: Unresolved
    • Icon: P3: Somewhat important P3: Somewhat important
    • None
    • 6.10
    • Core: Other
    • All
    • PM Spotted

      When you try to follow a "No Plain new()" rule to enforce the us of smart pointer and to follow the C++ Core Guidelines rule https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i11-never-transfer-ownership-by-a-raw-pointer-t-or-reference, the Qt library is hard to use because of the otherwise really great QT Object tree ownership. The concept is somehow in the opposite direction of the classic ownership. From the interface, the new object stores a parent, the parent does not explicit stores and owns the new object. You can think of the Qt object tree as the owner instead.   

      Here is post on Stackoverflow about plain new(): 
      https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new

      The Qt Object tree leads to code like this:

      m_pButtonMenu = new QMenu(this);

      with QMenu* m_pButtonMenu without explicit annotated ownership for the rest of the code.

      You might be tempted to fix it by

      m_pButtonMenu = std::make_unique<QMenu>(this);

      This works, but creates now a pointer with two owners which makes the issue worse, violating other rules in turn.

      1. "this" object
      2. Qt Object tree

      (The object tree is smart enough to handle it gracefully.)

      In Mixxx, we have introduce parented_ptr to fix this issue.

      parented_ptr<QMenu> m_pButtonMenu;
      ...
      m_pButtonMenu = make_parented<QMenu>(this);

      https://github.com/mixxxdj/mixxx/blob/main/src/util/parented_ptr.h

      This recognizes the parent ownership semantically and asserts that no QObject is created without Qt Object tree ownership.

      We use it in Mixxx now successful for 9 years and it has proven to be really helpful in code reviews and eliminates the risk of memory leaks due to missing parents we where suffering at the beginning.

       

      I suggest to adopt this parented_ptr() type for Qt itself.

       

      What do you think? 

      What is the correct process to get this in, who needs to be convinced before doing all the work that is required for that?  

       

       

       

       

       

       

       

       

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

            thiago Thiago Macieira
            daschuer Daniel Schürmann
            Vladimir Minenko Vladimir Minenko
            Alex Blasche Alex Blasche
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:

                There are no open Gerrit changes