PDA

View Full Version : Smart Pointer Design



lexfridman
18th January 2011, 00:49
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:


QWidget * foo;
foo = new QWidget();
foo = new QWidget();


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:



shared_ptr<QWidget> foo;
foo = shared_ptr<QWidget>(new QWidget());
foo = shared_ptr<QWidget>(new QWidget());


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

ChrisW67
18th January 2011, 01:41
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.