I can declare something like:
QString string;
I can also declare:
QString * string;
string = new QString();
What is the difference, why should I use one instead of the other ?
I can declare something like:
QString string;
I can also declare:
QString * string;
string = new QString();
What is the difference, why should I use one instead of the other ?
An object created using new operator (i.e. created "on the heap") will exist in memory until you destroy it with delete operator. To operate on such object, you need a pointer.
The other kind of objects (i.e. created "on the stack", like this: QString string;), exist only within given scope. For example:Objects created on the stack will be destroyed for you, so you don't have to worry about memory leaks. This also means that if you want to use such object, you musn't let it go out of scope.Qt Code:To copy to clipboard, switch view to plain text mode
In short: you use pointers only if you want to keep your objects in memory for longer or if you want to use polymorphism, while all other objects you create on the stack.
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