How does the dynamically allocated pointers in QT coding are destroyed because we don't write a specific destructor for them?
To expand on Neox's answer, Qt has two methods for object management:
QObject tree structure
Managed pointer classes
And the two don't really mix very well for reasons which will become apparent.
QObjects can either be 'free' or have a parent. When a QObject has its parent set (either by providing the QObject constructor with a pointer to another QObject, or by calling setParent()) the parent QObject becomes the owner of the child QObject and will make sure any of its children are destroyed when it is. There are also several methods available to inspect child/parent relationships.
A separate method of managing dynamically allocated objects are the managed pointer classes which this paper explains quite well. To summarise though:
"The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction" and is therefore good when you need objects which have clear and obvious ownership and lifetime.
"The QSharedPointer class holds a strong reference to a shared pointer [and] will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it" and is therefore good when ownership is not as clear cut, but you want to make sure it doesn't get lost and become a memory leak. QWeakPointer can be used to share the pointer without implying any ownership.
As you can see, some of the guarded pointer classes can be used with a QObject tree, but you should make sure you read and understand the documentation thoroughly before doing so or you may end up with a corrupt data structure.
The short answer is:
QObjects organize themselves in object trees. When you create a QObject with another object as parent, it's added to the parent's children() list, and is deleted when the parent is.
Qt has a good docu about object hierarchy and ownership within the framework. You can read it here
Related
I want to use C++11 Smart Pointers in new projects, and encounter a problem. Many current projects still use raw pointers as parameters in their interface and have no interface for smart pointers, e.g. QMainWindow::setCentralWidget.
To keep type consistent, I have to pass the stored pointer from get() like this segment:
QMainWindow win;
std::shared_ptr<QWidget> scrollArea{ std::make_shared<QScrollArea>() };
// QScrollArea is a derived class of QWidget.
win.setCentralWidget(scrollArea.get());
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
Will it cause memory leak or other problems if some methods in Qt do that?
I've checked the latest C++ Standard CD and found nothing on that. Seems it's an undefined behavior.
If doing this is an undefined behavior and dangerous, is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
There's no such way in the general case. For each "legacy" interface you want to use, you must read its documentation to see how it interacts with ownership (which is what std smart pointers encapsulate). A single object can only be managed by one ownership scheme.
With Qt in particular, it's definitely not safe to mix smart pointers and Qt management. Qt's parent/child relationship between QObjects includes ownership semantics (children are deleted when their parent is), so you cannot safely mix this with any other ownership scheme (such as std smart pointers).
Note that the Qt docs you link to explicitly state that "QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time."
Unfortunately, if you are using an interface that uses raw pointers, you will need to consult the documentation to determine if the method does or does not take ownership of the provided pointer.
If the function takes ownership, then you must invoke .release() to transfer the ownership to the function. If the function does not take ownership, then you would pass the object with .get().
Will it cause memory leak or other problems if some methods in Qt do that?
It won't introduce a memory leak, since the memory is afterall released. However, since both QT and the shared_ptr would call delete on that memory, you would likely get some nice heap corruption (UB in general).
is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
Sure. Don't have unrelated entities manage the same memory. For that it is adavantegous to use unique_ptr instead of shared_ptr when possible. With unique_ptr you could call .release() to release the memory from the control of the smartpointer, thus giving you the ability to give control over to QT.
Of course you need check the documentation to see when you have to manage memory yourself and when QT will do it for you.
I don't think you should be doing any deleting with the QWidget.
http://qt-project.org/doc/qt-4.8/qmainwindow.html#setCentralWidget
Note: QMainWindow takes ownership of the widget pointer and deletes it
at the appropriate time.
If you have to use smart pointers, you can use a weak_ptr which won't own or destroy it.
If you are using an interface which takes raw pointers, you already have the problem that you must know who is responsible for the lifetime of those pointers.
Adding shared_ptr into the mix doesn't change this.
If the interface will possibly delete the object, then you cannot use std::shared_ptr safetly. std::shared_ptr must control the lifetime of its objects and there's no way around this (without adding another level of indirection)
You can however get some use out of std::unique_ptr. If an interface will not delete a pointer, you can safetly pass in ptr.get(). If an interface takes ownership of the lifetime of that object, pass in ptr.release() and you give up controlling the lifetime yourself.
All in, you can get some usefulness out of smart pointers even with a legacy codebase, but you've got to be a little careful.
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
If the widget has a parent, then the QT's memory management will release that object. In that case you must not use a smart pointer, because your application will try to release it twice, and that is an undefined behaviour.
I was reading through the wxWidgets tutorial: http://docs.wxwidgets.org/trunk/overview_helloworld.html
And I noticed that they use new without delete. How is this possible :S How can you use new on a class without deleting it :S It doesn't make any sense to me :l
Can someone explain what's going on?
At the end of a program's execution, all memory in the process' memory space is freed by the OS.
It is likely that the tutorial showed you a simple example that requires the instantiated objects live until the end of the program.
For example, creating the window for the program will live until the program exits. So it is not necessary to delete this since the OS will do it for you.
I am not saying this is good practice, I always suggest that you explicitly take care of freeing memory to get in good habits.
There are other options in c++, such as smart pointers, which handle deletion of objects when refcounts reach 0, but I don't think that is what is happening here.
Some class libraries have a rule which gives the ownership of pointers as children to a parent object.
In this case, when you new an object and pass it to an owner object, it is the task of the owner to delete the pointer.
For example, a widget object adds GUI controls in its children-list, when the owner is going to be deleted, its destructor delete the children.
Read the documentation of wxWidgets about avoiding memory leaks:
Child windows
When a wxWindow is destroyed, it automatically deletes all its
children. These children are all the objects that received the window
as the parent-argument in their constructors.
As a consequence, if you're creating a derived class that contains
child windows, you should use a pointer to the child windows instead
of the objects themself as members of the main window.
You CAN use New without Delete, but only if you want the lifetime of the object to last until the program exits. Generally, it IS considered bad form.
Yes, it's possible to use new without calling delete but in general it's bad form. However just because you call new without explicitly calling delete yourself does not mean it is not called. In regards to GUI frameworks many of them handle calling delete internally based on external events. For instance if you call new to create an object that represents a window the GUI framework may call delete when the OS destroys the window. It may not be obvious unless you are familiar with the framework or read the documentation for it.
There are also "smart pointers" which are objects that hold a pointer to a particular resource and release (delete) it when the smart pointer itself is destroyed. Boost and C++11 provide implementations of smart pointers (std::unique_ptr for instance) which are used quite often to manage the lifetime (and ownership) of objects created using new. This of course is a generalization of smart pointers as there are various implementations that use reference counting or other mechanisms to ensure that the resource is released only when it is no longer used.
There are many articles floating around the web concerning smart pointers, resource lifetime, resource ownership, etc. A quick Stackoverflow or Google Dance for "C++ smart pointers" will give you a vary large list of resources for further reading. Searching for the acronyms RAII and SBRM will also bring up a large list of resources.
This has got to do with the way the wxFrame class is implemented. The object will be deleted when the frame is closed.
Quoting the wxWidgets documentation:
The default close event handler for wxFrame destroys the frame using Destroy().
Typically you do need to delete objects you allocate with the new, but in this case someone else is doing it for you.
Im thinking of starting using smart pointers in my qt work.The thing that confuses me how smart pointers would go with Qt garbage collection. The whole Qt stands on idiom that child QObject constructs with QObject* parent as ctor argument and therefore enables garbage collection.
For example:
QWidget* mWidget = new QWidget(this);//Here we not only
//ensure that mWidget will be deleted
//when its parent is deleted, but also tell qt,
//that mWidget is not a window, but belongs to
//parent's layout
Now if i want to wrap mWidget into the smart pointer.
typedef QScopedPointer<QWidget> WidgPtr;
WidgPtr mWidget = WidgPtr(new QWidget(this));
But now when parent's dtor is called it will call delete on mWidget's pointer twice. First due to garbage collection, second when smart pointer dtor is called.
Of course we can construct mWidget without parent and then change some flags to turn off window behaviour or call setParent() (But then again mWidget will be deleted twice). But to me its too much to do such a complex initialization only to be able to use smart pointers instead of raw pointers.
Or maybe i miss something?
Thanks.
QScopedPointer and QSharedPointer are not aware of whether their target object lives or dies, so if you keep the smart pointer anywhere else than among member variables, then yes, in your case destructor might be called twice. That's why these kinds of smart pointers are badly suited for QObjects (but they can still be useful when your object doesn't have a parent).
If you need to keep a guarded pointer to QObject, use QPointer: it will become null once the object is destroyed, so you can delete it at any moment without fear of causing any mayhem. But remember that QPointer will NOT destroy referenced object in destructor. In most cases you should build hierarchies of QObjects and just let the ownership system clean up the memory.
According to the Qt documentation:
QObjects organize themselves in object trees. When you create a
QObject with another object as parent, the object will automatically
add itself to the parent's children() list. The parent takes ownership
of the object; i.e., it will automatically delete its children in its
destructor.
For me that implies when a QObject is being deleted, it goes through and calls delete on all the pointers it stores in its children list.
However, it is not necessary for children to be dynamically allocated, and it is perfectly legal to build QObject trees with stack allocated objects.
According to standard specifications, calling delete on a pointer that does not point to a dynamically allocated object is undefined behavior, which may result in anything from "nothing" to a program crash.
IMO it is unlikely for QObject, which is pretty much the backbone of the almost the entire collection of Qt classes to rely on something that could produce undefined behavior.
So, does QObject distinguish between stack and heap allocated children when deleting? And if so, how exactly?
However, it is not necessary for children to be dynamically allocated,
and it is perfectly legal to build QObject trees with stack allocated
objects.
No. See QObject::~QObject():
Warning: All child objects are deleted. If any of these objects are on
the stack or global, sooner or later your program will crash.
I've been building a system with a parent object, where it creates various child objects, and each child object requires a master object to function. Now, so far, I've been creating shared_ptr<Parent> and Child*, so when the creator of Parent and all the Childs are gone, the Parent goes too.
But I'm re-designing my API so that Child can be created on the stack (previously it was just the heap). Now I'm unsure about what to do with Parents, as I don't see why they shouldn't also be creatable on the stack- in terms of their actual function- but what happens if Parent is destroyed and then someone tries to use a Child that they moved, copied, or allocated on the heap? Should I just throw an exception? Skip performing the operation? Or just stick to allocating Parents on the heap?
Here's the problem sentence
if Parent is destroyed and then someone tries to use a Child ...
If this is possible then you have shared ownership, which implies creation on the heap.
So, either you stick to heap allocation or drop the shared ownership semantics. There is no other way. weak_ptr is merely away of advertising the state of a shared object.
If you really want to do what you're advertising:
if Parent is destroyed and then someone tries to use a Child ...
This is going to cause a problem as #spraff mentioned.
The way to achieve what you are saying is to also make the Child a shared_ptr and allow a shared ownership between the Parent and also whatever else is trying to use the child...