Results 1 to 2 of 2

Thread: Smart Pointer Design

  1. #1
    Join Date
    Mar 2008
    Posts
    7
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Smart Pointer Design

    I've looked around on this forum and the web in general and have not found a clear discussion of using smart pointers with Qt objects. I am surprised to see most Qt examples using standard pointers. Does Qt perform some garbage collection?

    Example:
    Qt Code:
    1. QWidget * foo;
    2. foo = new QWidget();
    3. foo = new QWidget();
    To copy to clipboard, switch view to plain text mode 

    Will the first object float around in memory or be cleaned up?

    If it's a leak, should I instead use something like Boost's shared_ptr:

    Qt Code:
    1. shared_ptr<QWidget> foo;
    2. foo = shared_ptr<QWidget>(new QWidget());
    3. foo = shared_ptr<QWidget>(new QWidget());
    To copy to clipboard, switch view to plain text mode 

    I apologize if this question is ignorant of the underlying Qt design and/or has been answered thoroughly elsewhere on the forum.

  2. #2
    Join Date
    Mar 2009
    Location
    Brisbane, Australia
    Posts
    7,729
    Thanks
    13
    Thanked 1,610 Times in 1,537 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows
    Wiki edits
    17

    Default Re: Smart Pointer Design

    Your example would cause a leak, but then you won't see that in any of the Qt examples. Either each new QWidget/QObject will be created with a parent QWidget/QObject (which is typically an optional argument to the constructor) or be immediately given to something that takes ownership (like a layout). Typically the application's main window is allocated on the stack and becomes the ultimate owner of most widgets. Have a look at the detailed description of the QObject docs.

    Qt also has its own range of smart pointers: QPointer, QSharedPointer etc.
    Last edited by ChrisW67; 18th January 2011 at 02:48. Reason: updated contents

Similar Threads

  1. Replies: 1
    Last Post: 4th December 2010, 18:20
  2. smart pointers in Qt and Boost
    By pospiech in forum Qt Programming
    Replies: 0
    Last Post: 18th April 2010, 15:24
  3. Qt 4.6: Which Qt smart pointer to use for this case?
    By ShaChris23 in forum Qt Programming
    Replies: 1
    Last Post: 12th November 2009, 04:11
  4. Smart Code completion , making default
    By udit in forum Qt Tools
    Replies: 1
    Last Post: 14th September 2009, 11:08
  5. Replies: 3
    Last Post: 6th October 2008, 00:41

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.