Why do Qt use pointers instead of simple variable objects?
-
I'm a newbie on Qt, and sometimes i hesitate choosing between using pointers or simple variable objects.
But as i see all the examples in Qt documentation, there are almost always pointers, so i use pointers, but don't know why really i use pointers? Is there an explanation, do i missed something, somewhere ? I know the general meaning of a pointer in c++ but don't see the link with the use in Qt...? Maybe, i know my lessons good but my practical vision is quite bad !
Thks in advance :) -
Pointers are used because the copy constructor and affectation operator are by designed not implemented in the QObject class.
-
If you create Qt objects yourself, it's up to your own choice whether you create the object as an "auto" object (that's probably what you call "simple variable objects") or whether you create it on the heap (via "new" operator, so you get a pointer to the object). What method is preferable depends on the individual situation. Note that local "auto" objects are created on the stack. On the one hand this may have a smaller overhead as compared to allocating the memory on the heap. On the other hand, you might not want to create "big" objects on the stack. Also "auto" objects get destroyed, as soon as they go out of scope, while objects on the heap persist until you destroy them explicitly. Both has it's pros and cons. Again: It depends on the situation what is preferable!
Furthermore: Many functions in Qt that take an object as argument, actually take a pointer to an object. That's because passing an object "by value" would actually create a copy of the object (via copy constructor) and pass that copy! Creating a new copy of the object has a lot of overhead. At the same time, passing the object "by reference", i.e. as a pointer, will just pass a 32-Bit memory address, which is a very lightweight operation.
In addition to that, in many cases you want to pass exactly that object to the function, not some copy of it ;-)
--
-
Thks for responses, it's more clear now :)