[ fromfile: memberselect.xml id: memberselect ]
There are two forms of the member selection operator:
pointer->memberName
object->memberName
They look the same, but differ in the following ways.
The first is binary, the second is unary.
The first is global and not overloadable, the second is an overloadable member function.
When it is defined for a class, the unary operator->() should return a pointer to an object that has a member whose name is memberName.
An object that implements operator-> is typically called a smart pointer.
Smart pointers are so called because they can be programmed to be “smarter” than ordinary pointers.
For example, a QPointer is automatically set to 0 when the referenced object is destroyed.
Examples of smart pointers include
STL style iterators
QPointer, the Qt 4 smart pointer
auto_ptr, the STL smart pointer
All of these smart pointers are template classes.
Example 19.12 shows the class definition of QPointer.
Example 19.12. src/pointers/autoptr/qpointer.h
[ . . . . ] template <class T> class QPointer { QObject *o; public: inline QPointer() : o(0) {} inline QPointer(T *p) : o(p) { QMetaObject::addGuard(&o); } inline QPointer(const QPointer<T> &p) : o(p.o) { QMetaObject::addGuard(&o); } inline ~QPointer() { QMetaObject::removeGuard(&o); } inline QPointer<T> &operator=(const QPointer<T> &p) { if (this != &p) QMetaObject::changeGuard(&o, p.o); return *this; } inline QPointer<T> &operator=(T* p) { if (o != p) QMetaObject::changeGuard(&o, p); return *this; } inline bool isNull() const { return !o; } inline T* operator->() const { return static_cast<T*>(const_cast<QObject*>(o)); } [ . . . . ]
The operators makes use of two ANSI-style typecasts: (Section 19.7) static_cast and const_cast.
const_cast is required because the function is const, and it must return a non-const pointer.
RTTI is not necessary here because the template ensures that the actual pointer stored was a T*.
Therefore, static_cast can be used instead of dynamic_cast.
A QPointer<T> is said to be a guarded pointer to a QObject of type T.
By guarded we mean that the QPointer is automatically set to 0 if the object that it is pointing to is destroyed.
Here is a code fragment that demonstrates how a QPointer can be used.
[. . .] QPointer<QIntValidator> val = new QIntValidator(someParent); val->setRange(20, 60); [. . .]
In the second line of code, val-> returns a pointer to the newly allocated object, and it is used to access the setRange() member function.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |