简体   繁体   中英

Qt Creator / C++ does valgrind make sense in this case

I'm used to using valgrind to debug my C code, but I recently switch to Qt Creator and C++. Qt Creator has valgrind built in which sounds good but...

if I don't malloc/free memory directly (ie only use C++'s built in memory cleanup upon no more references to objects), shouldn't memory leaks be impossible?

How could I cause a memory leak if C++ is managing the objects and memory....

(I fear a RTFM answer, but scratching head)


What about something like this:

m_logFile = new QFile(programSettings->logging_filename());

would I have to free what this pointer points to, or when m_logFile no longer points to a valid object will the memory be freed? (Since I use 'new' here I wonder if it works differently)

Yes, in this case valgrind is still useful. C++ (even with Qt) is still not a garbage collected language, so you can still accidentally leak memory. In the example code you gave, the QFile will leak as nothing will destroy it (by using the delete operator).

Qt does provide a method to help cleanup any QObject derived classes. However, you still need to pass the correct object as the parent object for the cleanup to work.

Also, valgrind will also help identify any incorrect uses of uninitialised or freed memory.

Qt's memory management is only automatic for QObject hierarchies, where the parent owns the children. As long as you destruct the parent, all of the children will get deleted. This of course applies to QWidgets , as they are QObject s. Technically, you could make just a QObject be a parent of a QWidget , but it breaks down the assumptions that widgets have about their parents, so don't do that. A QWidget can of course own QObject s.

Here's the very important detail : it's the destruction of the parent that destructs and deletes the children. The parent may be an automatic variable, and then the memory is deallocated automatically upon leaving the scope. If the parent is allocated on the free store using new , you've got yourself a memory leak unless:

  1. You manually delete the parent.
  2. You use a smart pointer.

Generally speaking, using naked pointers in C++ should be avoided. Qt provides a QSharedPointer that's mostly equivalent to C++11's std::shared_ptr , and a QScopedPointer that's mostly equivalent to C++11's std::unique_ptr . Use them unless you've got measurements showing that manual memory management will win you something in terms of performance or memory overhead. Those smart pointers perform the exception-safe memory management for you.

I think you would benefit from reading Strostrup's "The C++ Programming Language", 4th edition. It introduces those concepts with more depth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM