Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: does "new without delete" cause memory leaks with controls?

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?

like image 574
sivabudh Avatar asked Oct 30 '09 18:10

sivabudh


People also ask

Which condition causes memory leak?

Memory leaks are a common error in programming, especially when using languages that have no built in automatic garbage collection, such as C and C++. Typically, a memory leak occurs because dynamically allocated memory has become unreachable.

Does every new need a delete?

However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination. Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete guarantees the destruction in these cases.

Does function create memory leak?

No it does not cause memory leaks.

How would you prevent a memory leak?

To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.


2 Answers

No, the addWidget() function will keep ownership of the widget. It will then destroy the widgets it owns.

Additionally you can read here that:

As with QObjects, QWidgets 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 widget is displayed within the screen area occupied by its parent widget. This means that when you delete a window widget, all the child widgets it contains are also deleted.

like image 87
Klaim Avatar answered Oct 13 '22 19:10

Klaim


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);
like image 27
Marcel Gosselin Avatar answered Oct 13 '22 18:10

Marcel Gosselin