[ fromfile: memberselect.xml id: memberselect ]
There are two forms of the member selection operator:
pointer->memberName
object->memberName
They look similar but differ in important 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 QSharedPointer is a smart pointer that maintains reference-counting pointers to QObject.
The shared QObject is deleted if the last shared pointer is deleted.
Examples of smart pointers include
STL style iterators
QPointer, QSharedDataPointer, QSharedPointer, QWeakPointer, QScopedPointer, QExplicitlySharedDataPointer
auto_ptr
, the STL smart pointer
These smart pointers are all template classes.
Example 19.24 shows part of the definition of QSharedPointer.
Example 19.24. src/pointers/autoptr/qsharedpointer.h
template <class T> class QSharedPointer { public: QSharedPointer(); explicit QSharedPointer(T* ptr); T& operator*() const; T* operator ->() const; bool isNull() const; operator bool() const; bool operator!() const; // [ ... ] };
<include src="src/pointers/autoptr/qsharedpointer.h" href="src/pointers/autoptr/qsharedpointer.h" id="qsharedpointerh" mode="cpp"/>
A pointer<T> is said to be a guarded pointer to a QObject of type
T
if the pointer is automatically set to 0 when its object is destroyed.
QSharedPointer, QPointer, and QWeakPointer all provide this functionality as well.
Here is a code fragment that shows how a smart pointer can be used in a similar way to a regular pointer:
[. . .] 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: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |