views:

344

answers:

3

I was looking at Qt example here:

and inside the constructor, they have:

 Window::Window()
 {
     editor = new QTextEdit();   // Memory leak?
     QPushButton *sendButton = new QPushButton(tr("&Send message")); // Memory leak?

     connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));

     QHBoxLayout *buttonLayout = new QHBoxLayout();  // Memory leak?
     buttonLayout->addStretch();
     buttonLayout->addWidget(sendButton);
     buttonLayout->addStretch();

     QVBoxLayout *layout = new QVBoxLayout(this);    // Memory leak?
     layout->addWidget(editor);
     layout->addLayout(buttonLayout);

     setWindowTitle(tr("Custom Type Sending"));
 }

Those lines with comments

// Memory leak?

aren't those memory leaks?

If so, since the Window class has no constructor, then I should make all of those variables (editor already is) Window member variables ?

Or..does Qt internally "delete" those member variables when it goes out of scope?

+12  A: 

No : the addWidget() function will keep ownership of the widget. It will then destroy the widgets it have ownership on.

Additionally you can read there that :

As with QObjects, widgets can be created with parent objects to indicate ownership, ensuring that objects are deleted when they are no longer used. With widgets, these parent-child relationships have an additional meaning: each child is displayed within the screen area occupied by its parent. This means that, when a window is deleted, all the widgets it contains are automatically deleted.

Klaim
+1 I was guessing in my deleted answer :)
AraK
+4  A: 

If there is an exception thrown between new and addWidget then yes there is a memory leak. Otherwise the parent control takes ownership of the memory.

QHBoxLayout *buttonLayout = new QHBoxLayout();  // Memory leak?
//make sure you don't throw here
buttonLayout->addWidget(sendButton);
Marcel Gosselin
+4  A: 

In addiction to @Klaim correct answer:

I would store those pointers in a std::auto_ptr meanwile you pass them to their parent.

std::auto_ptr<QHBoxLayout> buttonLayout( new QHBoxLayout() );
// make things which could throw...
layout->addLayout(buttonLayout.release());

This way you are sure don't have leaks.

fnieto
Even better than my own answer
Marcel Gosselin
oh wow..i've never thought in that detail before. thanks!
ShaChris23
Won't it get double-deleted if you do this?Once by auto_ptr, then again by QObject?
James