19.11.  Member Selection Operators

[ fromfile: memberselect.xml id: memberselect ]

There are two forms of the member selection operator:

  1. pointer->memberName

  2. object->memberName

They look similar but differ in important ways.

  1. The first is binary, the second is unary.

  2. 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

  1. STL style iterators

  2. QPointer, QSharedDataPointer, QSharedPointer, QWeakPointer, QScopedPointer, QExplicitlySharedDataPointer

  3. auto_ptr, the STL smart pointer

These smart pointers are all template classes.

Example 19.21 shows part of the definition of QSharedPointer.

Example 19.21. 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;  
    // [ ... ]
};

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.