News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ array tips - Should operator[] return a reference or pointer?

Started by ben2ong2, October 06, 2006, 06:09:42 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: You are not allowed to view links. Register or Login

I have an array class which is a more memory efficient array, in which array
elements do not always actually exist in memory.

Therefore, I overloaded the operator[] with the prototype:
      myarrayelement* operator[](int);

This returns a pointer to the array element if it exists, or a NULL pointer
if it does not.

However the conventional operator[] should return a reference, but I
cannot return a refence if the array element does not exist.

I get around this problem by having a member of my arrayclass which is
in fact a null myarrayelement and If the element requested does not
exist, I return a reference to this null element.

My question is: Is it better to change the style of the operator[] to return
a pointer, or should should I return a reference to a null object?


RESPONSE: You are not allowed to view links. Register or Login (James Kanze), 23 Aug 95

Neither.

What you are doing is called sparce arrays, and the usual solution is
to return a proxy, i.e.: an object of a helper class.

Basically, the actual array access would be via two functions, put and
get.  (It is up to you to decide what these functions mean if the
element is not present.  In my case, get returns 0, and put creates
the element.)

The operator[] returns an instance of a proxy class.  This class is
defined as follows:

1. The constructor simply stores the parameters of operator[] and a
pointer to the array object in private data.

2. A conversion operator allows automatic conversion to the type
contained in the array.  It simply calls get, and returns the value it
gets (by value).  It will be called implicitly in most rvalue
contexts.

3. The operator= is overloaded to take a value of the type stored in
the array.  It calls put with this value.

If the array contains numeric types, you may want to overload
operators like +=, -=, etc. so that they will work too.

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login