Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 27.  Subscript Operators


27.3. Return Value

So we've decided on a reasonable strategy for index validation, but there still remains the issue of what we actually return from the subscript operator. Thankfully, the use of the canonical &c[0] makes this pretty simple. We must return something that, when subject to the address-of operator (unary operator &), will yield a pointer to the managed sequence. Hence Double Container returns double& or double const &, either of which will yield a pointer when subjected to the address of operator.

I don't know how many of you have done as I have in the past and written naïve pre-STL containers that returned by value, as in:



class DoubleContainer


{


  . . .


  double operator [](size_t index) const;



This is simply not good enough. If you return by value, you're introducing a disconnect between the managed sequence and the client code that may wish to meaningfully apply the address-of operator to get a pointer to the managed sequence.

That's not to say that you must return a reference. An alternative strategy is to return an instance that can act as a reference. For example, DoubleContainer's operator []() could return an instance of DoubleIndexProxy:



class DoubleIndexProxy


{


  . . .


  double *operator &();


  double const *operator &() const;



As you can see, this goes against the advice of the last chapter, which is to eschew the overloading of operator &(). In this case, it's fine because no one in their right mind will be attempting to put a DoubleIndexProxy in a container, or indeed use it for any other purpose. In fact, it would be a private nested class within DoubleContainer, so no one can access it save the compiler, and she'll faithfully follow your access control dictates.

This seems a reasonable principle, but it falls on its face a bit when we try to use this with multidimensional arrays (see Chapter 33).


      Previous section   Next section