PROBLEM: What is the correct syntax for using delete on an array of objects?
char* s = new char [40];
delete s;
int *p = new int [40];
delete 40 p;
RESPONSE: Anil A. Pal (pal@wpd.sgi.com)
Actually, both of these examples are incorrect as of the latest draft
of the C++ standard. The correct way (for both cases) is:
mumble* x = new mumble[40];
delete [] x;
Earlier implementations of C++ (for example, those based on cfront 2.0 or
before) required the programmer to explicitly supply the count (40) in the
delete.
delete [40] x;
What happens if you forget and do a simple delete x; ? Well, for the
examples quoted (int and char) usually nothing dramatic. The full
storage will probably be returned to the free pool (in typical
malloc/free based implementations).
If the type mumble is a class with a destructor, however, forgetting the
array form of the delete will result in a SINGLE DESTRUCTOR being called,
for the 0-th element in the array.
Using the array syntax (delete [] x;) will correctly call the destructor
for all elements of the array.
TITLE: Distinguishing lvalue/rvalue for operator []
PROBLEM: Is there any way to distinguish when the operator[] is used
as an lvalue as opposed to an rvalue?
RESPONSE: Joe Buck (jbuck@galileo.berkeley.edu)
class ElementRef {
operator int ();
operator=(int);
};
class IntVector {
...
ElementRef operator[] (int);
};
The idea is that [] returns a special class called ElementRef, which
has two operators defined: assignment operator and cast-to-int.
If I say
IntVector v;
int i, j;
...
v[3] = i;
j = v[4];
in the first case, ElementRef::operator=(int) is used. In the
second case, ElementRef::operator int() is used.