Very good explanation, now:
I have looked at some books about Qt, the ones I know of show always something like:
QTextBrowser *textBrowser;
Why ?
In the ".h" class couldn't I just do:
QTextBrowser textBrowser;
????
Very good explanation, now:
I have looked at some books about Qt, the ones I know of show always something like:
QTextBrowser *textBrowser;
Why ?
In the ".h" class couldn't I just do:
QTextBrowser textBrowser;
????
You could but this has two disadvantages:
1. You have to include all header files needed by the class in every file that uses your class
2. The order of destroying objects depends on the compiler. If it destroys objects in a wrong order, you'll get a memory error, because an area of memory will be freed twice. Consider this example:
If compiler first frees w1 and then w2 then everything will be ok - w1 will be destroyed, so it will detach from its parent and then w2 will be destroyed.Qt Code:To copy to clipboard, switch view to plain text mode
If the order is w2 and then w1, then when w2 is destroyed, it will destroy all its children including w1, so w1 will be destroyed as well. But the compiler doesn't know that w1 has already been destroyed, so will proceed normally and will try to delete w1, which will result in a double-free and a memory error.
So... what is the best approach:
QTextBrowser textBrowser;
or
QTextBrowser *textBrowser
???
It depends on the situation. It is safe to use pointers in every situation, but sometimes it is not required to do so (for example for widgets that don't have a parent or that will be destroyed earlier than their parents). There is really no "better". Qt handles most memory management for you, so you even don't have to remember about releasing the memory yourself, hence using "new" is not a big effort and can save your butt when writing for platforms that have a limited stack space![]()
Bookmarks